Swap Counter in simple Selection Sort method

    void sortSelection(List object)
         int swapCount=0;
           for(int i = list.length; i >= 2; i--)
             int maxIndex = 0;
                    for(int j = 1; j < i; j++)
                         if(list[j] > list[maxIndex])
                              maxIndex = j;
               int temp = list[maxIndex];        //
               list[maxIndex] = list[i-1];         //         Is the problem here?        
               list[i-1] = temp;                     //
               swapCount++;                     //
          System.out.println("\n" +swapCount+ " swaps were needed. ");
    }This is a pretty simple selection sort method. But I am fairly sure that I am incorrectly counting swaps with the code. I have defined a "swap" as when two array indices have their values switched. I am convinced that there is something wrong because the array of numbers is randomly generated, and yet the swapCount counter is always equal
to (list.length-1) when it prints out. I would think it should be different every time. I indicated the line where I believe the problem lies, but I am not for sure. Thanks everybody.

List of Random Integers, then sorted:
9, 29, 30, 42, 53, 58, 59, 64, 66, 69, 74, 79, 79, 87, 95
9 swaps were needed.then sort again (descending) and get this:
95, 87, 79, 79, 74, 69, 66, 64, 59, 58, 53, 42, 30, 29, 9
1 swaps were needed.I'm pretty sure that isn't correct. But forgive me if I did not specify that it was to work in descending order as well.
So I tried this:
void sortSelection(List object)
         int swapCount=0;
           for(int i = list.length; i >= 2; i--)
             int maxIndex = 0;
                    for(int j = 1; j < i; j++)
                         if(list[j] > list[maxIndex])
                              maxIndex = j;
              if (maxIndex != (i-1) && ascending==true)
                   int temp = list[maxIndex];
                    list[maxIndex] = list[i-1];                             
                    list[i-1] = temp;   
                    swapCount++;
              else if (maxIndex != (i+1) && descending==true)
                   int temp = list[maxIndex];
                    list[maxIndex] = list[i-1];                             
                    list[i-1] = temp;   
                    swapCount++;
} adding the i+1 (because it is going in a different order)...and I think I solved it!

Similar Messages

  • Sorting a vector using the selection sort method

    I have to write a program that sorts a Vector using the selection sort algorithm. Unfortunately the textbook only has about 2 pages on vectors so needless to say I'm pretty clueless on how to manipulate vectors. However I think I'm on the right path, however I'm stuck on one part as shown in the code below.     
    private static void  selectionSort(Vector parts)
          int index;
            int smallestIndex;
            int minIndex;
            int temp = 0;
            for (index = 0; index < parts.size() - 1; index++)
              smallestIndex = index;
              for (minIndex = index + 1; minIndex < parts.size(); minIndex++)
               if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex))  // this is where I'm having trouble
                  smallestIndex = minIndex;
                parts.setElementAt(temp, smallestIndex);
                parts.setElementAt(smallestIndex, index);
                parts.setElementAt(index, temp); if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex))
    is returning "ProcessParts3.java:51: operator < cannot be applied to java.lang.Object,java.lang.Object"
    Here is the full program:
    import java.util.*;
    import java.io.*;
    public class ProcessParts3
         static Vector parts;
         public static void main(String[] args)
              loadVector();
         private static void loadVector()
         try
              Scanner fileIn = new Scanner(new File("productionParts.txt"));
              parts = new Vector();
              String partIn;
              while (fileIn.hasNext())
                   partIn = fileIn.nextLine();
                        parts.addElement(partIn.trim());
              selectionSort(parts);
                   for (int i = 0; i < parts.size(); i ++)
                   System.out.println(parts.elementAt(i));
         catch(Exception e)
              e.printStackTrace();
         private static void  selectionSort(Vector parts) //from this part down I'm responsible for the coding, everything
                                                               // everything above this was written by the teacher
                 int index;
            int smallestIndex;
            int minIndex;
            int temp = 0;
            for (index = 0; index < parts.size() - 1; index++)
                smallestIndex = index;
                for (minIndex = index + 1; minIndex < parts.size(); minIndex++)
                    if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex))
                        smallestIndex = minIndex;
                parts.setElementAt(temp, smallestIndex);
                parts.setElementAt(smallestIndex, index);
                parts.setElementAt(index, temp);
    }Edited by: SammyP on Nov 27, 2009 11:43 AM

    SammyP wrote:
    I have to write a program that sorts a Vector using the selection sort algorithm...Hmmm.... Your teacher is, in my humble opinion, a bit of a tard.
    1. Vector is basically deprecated in favor of newer implementations of the List interface which where introduced in [the collections framework|http://java.sun.com/docs/books/tutorial/collections/index.html] with Java 1.5 (which became generally available back in May 2004, and went end-of-support Oct 2009). ArrayList is very nearly a "drop in" replacement for Vector, and it is much better designed, and is marginally more efficient, mainly because it is not syncronised, which imposes a small but fundamentally pointless overhead when the collection is not being accessed across multiple threads (as is the case in your program).
    2. Use generics. That "raw" Vector (a list of Objects) should be a genericised List<String> (a list of Strings)... because it's compile-time-type-safe... mind you that definately complicates the definition of your static sort method, but there's an example in the link... Tip: temp should be of type T (not int).
    Note that String implements [Comparable<String>|http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html], so two String's can safely be compared using the compareTo method... In Java the mathematical operators (<, >, &#43;, -, /, &#42;, etc) are only applicable to the primitive types (byte char, int, float, etc)... The Java Gods just chose to muddy the waters (especially for noobs) by "overloading" the &#43; operator for String (and String only) to enable succinct, convenient string-concatenation... which I personally now see as "a little bit of a mistake" on there part.
         private static void  selectionSort(Vector parts)  {
    int index, smallestIndex, minIndex, temp = 0;
    for (index = 0; index < parts.size() - 1; index++) {
    smallestIndex = index;
    for (minIndex = index + 1; minIndex < parts.size(); minIndex++) {
    if (parts.elementAt(minIndex) < parts.elementAt(smallestIndex)) {
    smallestIndex = minIndex;
    parts.setElementAt(temp, smallestIndex);
    parts.setElementAt(smallestIndex, index);
    parts.setElementAt(index, temp);
    }3. ALLWAYS use {curly braces}, even when not strictly necessary for correctness, because (a) they help make your code more readable to humans, and also (b) if you leave them out, you will eventually stuff it up when you insert a line in the expectation that it will be part of the if statement (for example) but you forgot to also add the now mandatory curly-braces... This is far-too-common source of bugs in noob-code. Almost all professionals, nearly allways allways use curly braces, most of the time ;-)
    4. Variable names should be meaningful, except (IMHO) for loop counters... Ergo: I'd rename index plain old i, and minIndex to plain old j
        for ( int i=0; i<list.size()-1; ++i) {
          int wee = i; // wee is the index of the smallest-known-item in list.
          for ( int j=i+1; j<list.size(); ++j ) {Cheers. Keith.
    Edited by: corlettk on 28/11/2009 09:49 ~~ This here fraggin forum markup friggin sucks!

  • Help needed with a simple CompareTo sorting method

    This code is supposed to sort through a list of random numbers, dates, and strings to find the largest. The problem is that with the strings it just sets the first string in the array to the largest, and I'm really not sure why it's doing it...Any help would be appreciated. I am aware that this is a very simple problem..No need to tell me. ^_^;
    import java.util.Date;
    public class CompareToSort {
      public static void main(String[] args) {
    String[] strings = {"CS", "Math", "Biol", "Chem", "Phys", "Buss", "Law", "Educ", "Elec Engr", "Mech Engr"} ;
    Integer[] list = new Integer[10] ;
    Date[] dates = new Date[10] ;
    for (int i = 0; i < list.length; i++)
          list[i] = new Integer((int)(Math.random() * 100));
    for (int i = 0; i < list.length; i++)
          dates[i] = new Date();
    System.out.println("Max string is " + max(strings));
    System.out.println("Max integer is " + max(list));
    System.out.println("Max date is " + max(dates));
    public static Object max (Object[] a)
      Object currentMax = null;
      int currentMaxIndex;
      for(int i = a.length - 1; i>=0; i--)
         currentMax = a;
    currentMaxIndex = i;
    for (int j = i - 1; j >=0; j--)
    if (((Comparable)currentMax).compareTo(a[j]) < 0)
    currentMax = a[j];
    currentMaxIndex = j;
    return currentMax;

    I think your ten Dates are all same.
    import java.util.Date;
    public class CompareToSort {
      public static void main(String[] args) {
        String[] strings
         = {"CS", "Math", "Biol", "Chem", "Phys", "Buss", "Law", "Educ",
            "Elec Engr", "Mech Engr"} ;
        Integer[] list = new Integer[10] ;
        Date[] dates = new Date[10] ;
        for (int i = 0; i < list.length; i++){
          list[i] = new Integer((int)(Math.random() * 100));
        for (int i = 0; i < list.length; i++){
          dates[i] = new Date();
        System.out.println("Max string is " + max(strings));
        System.out.println("Max integer is " + max(list));
        System.out.println("Max date is " + max(dates));
      public static <T extends Comparable<T>> T max (T[] a){
        T currentMax = a[0];
        for(int i = 1; i < a.length; ++i){
          if (a.compareTo(currentMax) > 0){
    currentMax = a[i];
    return currentMax;

  • Selection Sort Method help

    The method below will not compile. The error reads" void is an invalid type for the variable selectionSort". What should I do? Also how would I invoke the method?
    public static void selectionSort(double[] score, String[] name)
             for (int i=scores.length-1; i>=1; i--)
               double currentMax=scores[0];
               int currentMaxIndex=0;
               for (int j=1; j<=i; j++)
                 if (currentMax<scores[j])
                   currentMax=scores[j];
                   currentMaxIndex=j;
               if (currentMaxIndex!=i)
                  scores[currentMaxIndex]=scores;
         scores[i]=currentMax;
         String temp=names[currentMaxIndex];
         names[currentMaxIndex]=names[i];
         names[i]=temp;
         }Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    meepton wrote:
    show me how.Why? you didn't write it, you don't understand it so I don't see any beneficial reason to help you. I suggest reading some tutorials about creating and using methods.
    Mel

  • Help needed badly for selection sort

    I posted this on the other forum but haven't gotten a reply. I have a class that compares the zip codes of a file that is read into the code and store as objects. Now I have to sort the information by the zip codes this is what I have so far and I do not know what I am doing wrong with the selection sort. This is the first time I am doing selection sort.
    Here is my .txt
    10
    Dillin Jake York PA 17409
    Valdir John Chicago IL 98098
    Morphy Bob Harrisburg PA 73829
    Spears Johnathan Chicago IL 09182
    Simpson Bloo Los Angeles CA 94840
    Griffin Taylor York IL 49283
    Cartmen Eric Philadelphia PA 28192
    Connaly Teds Springfield IL 12930
    Marsh Stan Miami FL 48392
    William Thomas Reno NV 39029
    and this is the code:
    import java.util.*;
    import java.io.*;
    import java.util.Scanner.*;
    public class TestCustomer6 {
      public static void main (String[] args) throws FileNotFoundException {
        Scanner scan = new Scanner (new File ("customerData.txt"));
        int numLines = scan.nextInt();
           Customer2[] customer;
         customer = new Customer2[40];
        for (int i = 0; i < numLines; i++) {
          String fName = scan.next();
          String lName = scan.next();
          String city = scan.next();
          String state = scan.next();
          int zip= scan.nextInt();
         Customer2 newObj = new Customer2(fName,lName,city,state,zip);
        customer=newObj;
    public static void selectionSort(int[] array)
    {int count;
       for (count = 0; count < array.length; count++)
          int indexOfMin = findMinimum (array, count);
           swap (array, count, indexOfMin );
         public static int findMinimum (int[] array, int startIndex)
    {int mycount;
         int indexOfMin = startIndex;
           for(mycount = startIndex + 1; mycount < array.length; mycount++)
              if (array[mycount] < array[indexOfMin]
    indexOfMin = mycount;
    return indexOfMin;
         public static void swap (int[] array, int preIndex, int nexIndex)
    double temp = array[preIndex];
    array[nexIndex] = array[preIndex];
    array[nexIndex] = temp;
    the class:
    import javax.swing.*;
    class Customer2{
        public static final int FNAME = 0;
        public static final int ZIP = 1;
        private static final int LESS = -1;
        private static final int EQUAL = 0;
        private static final int MORE  = 1;
        private static int compareAttribute;
         private String firstName;
         private String lastName;
         private String city;
         private String state;
         private int zip;
        static {
           compareAttribute = FNAME;
         public Customer2(){
         firstName = " ";
         lastName = " ";
         city = " ";
         state = " ";
         zip = 0;
         public Customer2(String f, String l, String c, String s, int z){
              this.firstName = f;
              this.lastName = l;
              this.city = c;
              this.state = s;
              this.zip = z;
              System.out.println(this.toString());
        public static void setCompareAttribute( int attribute ) {
            compareAttribute = attribute;
        public int compareTo( Customer customer, int attribute ) {
            int comparisonResult;
            if ( attribute == ZIP ) {
                int p2zip = customer.getZip( );
                if (this.zip < p2zip) {
                    comparisonResult = LESS;
                } else if (this.zip == p2zip) {
                    comparisonResult = EQUAL;
                } else {
                    assert this.zip > p2zip;
                    comparisonResult = MORE;
            } else { //compare the name using the String class�s
                    //compareTo method
                String    p2fname = customer.getFirst( );
                comparisonResult = this.firstName.compareTo(p2fname);
            return comparisonResult;
        public int compareTo( Customer customer ) {
            return compareTo(customer, compareAttribute);
         public String getFirst(){
              return firstName;
         public String getLast(){
              return lastName;
         public String getCity(){
              return city;
         public String getState(){
              return state;
         public int getZip(){
              return zip;
         public String toString(){
              return  getFirst() + ",  " + getLast() + "     " + getCity() + "     "
              + getState() + "     " + getZip();

    1) Your code doesn't compile;
    2) You don't call your selection sort method anywhere;
    3) Your selection sort attempts to sort an int array which doesn't make sense;
    4) You don't use the comparison methods defined in your Customer2 class;
    5) I think that you've just copied/pasted several code fragments;
    6) Your indentation style is highly inconsistent (also see 5).
    kind regards,
    Jos

  • Selection Sort using Linked Lists

    As the subject says, I'm trying to implement a selection sort method on a linked list structure. I've already created a bubble sort, but I can't seem to get this method to work correctly. The Node and LinkedList classes were written by me, and I know they work correctly (because of the other methods work right).
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                boolean exchangeMade;
                while (pointer.getNext().getNext() != null) {
                    current = pointer;
                    exchangeMade = false;
                    iterationsOUTER++;
                    while (current.getNext() != null && !exchangeMade) {
                        if(current.getNext().getData() < pointer.getData()) {
                            int temp = pointer.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            exchangeMade = true;
                            iterationsINNER++;
                            swaps++;
                            comparisons++;
                        current = current.getNext();
                    pointer = pointer.getNext();
              //  System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }For instance, if I run this bit of code...
    LinkedList list = new LinkedList();
            list.insert(5);
            list.insert(29);
            list.insert(2);
            list.insert(1);
            list.insert(13);
            list.insert(8);
            list.insert(30);
            list.insert(3);
            sort.selectionSort(list);
            list.print();The output is...
    1
    8
    13
    3
    2
    29
    30
    5
    Anyone have any idea what is going wrong, or is anymore information needed?
    PS: I also need to create a insertion sort method with this, and I've been told I need to reverse the list for the insertion sort to work correctly. Any tips on how to implement this method too? :)

    I've changed it up a bit, and it works, but is this still a bubble sort? I've tried uncommenting that section that keeps track of the iterations and such, but I know they can't be right. Does this look correct? I basically just removed that boolean check...
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                while (pointer.getNext() != null) {
                    current = pointer;
                    iterationsOUTER++;
                    while (current.getNext() != null) {
                        comparisons++;
                        if(current.getNext().getData() < pointer.getData()) {
                            int temp = pointer.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            iterationsINNER++;
                            swaps++;
                        current = current.getNext();
                    pointer = pointer.getNext();
                System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }And no, I tried and I don't get a NullPointerException if I have a list of 2.
    Edited by: birdboy30 on Dec 3, 2007 7:23 PM

  • Selection Sort Algorithm

    I'm trying to implement a selection sort method with linked lists, but I just can't seem to get it to work correctly.
    public void selectionSort(LinkedList list) {
            int iterationsINNER = 1, iterationsOUTER = 1, swaps = 0, comparisons = 1;
            if(list.isEmpty())
                System.out.println("List is currently empty.");
            else if (list.size() == 1)
                System.out.println("List is already sorted.");
            else {
                Node pointer = list.getFirst();
                Node current;
                boolean exchangeMade;
                while (pointer.getNext() != null) {
                    current = pointer;
                    exchangeMade = false;
                    iterationsOUTER++;
                    while (current.getNext() != null && !exchangeMade) {
                        if(current.getNext().getData() < current.getData()) {
                            int temp = current.getData();
                            pointer.setData(current.getNext().getData());
                            current.getNext().setData(temp);
                            exchangeMade = true;
                            iterationsINNER++;
                            swaps++;
                            comparisons++;
                        current = current.getNext();
                    pointer = pointer.getNext();
              //  System.out.println("Comparisons: " + comparisons + " \nSwaps: " + swaps + " \nIterations: " + iterationsINNER+iterationsOUTER);
        }If I test it with this code...
            LinkedList list = new LinkedList();
            list.insert(5);
            list.insert(29);
            list.insert(2);
            list.insert(1);
            list.insert(13);
            list.insert(8);
            list.insert(30);
            list.insert(3);
            sort.selectionSort(list);
            list.print();I get this as my output...
    8
    13
    1
    2
    29
    5
    30
    30

    Please clarify one thing for me:
    Is the Node class, something you made, or is it in the Java class library (there's quite a few named Node in there)? let me know....
    also, the LinkedList class has a generic type attached to it. Meaning you can store any data type in the LinkedList, but you have to specify what you want.
    example:
    LinkedList<String> strings = new LinkedList<String>();since the list is a parameter you don't have to initialize it, however you still need to specify what data type you're dealing with. I'd use "LinkedList<Object>" if you're not sure what type a user of this method may select, but it looks like you're gonna want to use "LinkedList<Node>".

  • A simple select query taking forever

    Hi All
    I am not able to execute a simple select query, I traced my session and here is TKPROF of that Trace.
    Solaris 8 , Oracle 10.2.0.4.0
    TKPROF: Release 10.2.0.4.0 -
    Copyright (c) 1982, 2007, Oracle.  All rights reserved.
    Trace file: 502_ora_28260.trc
    Sort options: default
    count    = number of times OCI procedure was executed
    cpu      = cpu time in seconds executing
    elapsed  = elapsed time in seconds executing
    disk     = number of physical reads of buffers from disk
    query    = number of buffers gotten for consistent read
    current  = number of buffers gotten in current mode (usually for update)
    rows     = number of rows processed by the fetch or execute call
    select OBJECT_ID , ORACLE_USERNAME , SESSION_ID
    from
      v$locked_object
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.00       0.00          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch        1      0.03      32.86          0          0          6           0
    total        3      0.03      32.86          0          0          6           0
    Misses in library cache during parse: 1
    Optimizer mode: CHOOSE
    Parsing user id: SYS
    Rows     Row Source Operation
          0  MERGE JOIN  (cr=0 pr=0 pw=0 time=60 us)
          0   SORT JOIN (cr=0 pr=0 pw=0 time=58 us)
          0    MERGE JOIN  (cr=0 pr=0 pw=0 time=42 us)
          1     SORT JOIN (cr=0 pr=0 pw=0 time=2443 us)
       1105      FIXED TABLE FULL X$KSUSE (cr=0 pr=0 pw=0 time=1204 us)
          0     SORT JOIN (cr=0 pr=0 pw=0 time=41 us)
       1001      FIXED TABLE FULL X$KTCXB (cr=0 pr=0 pw=0 time=16132 us)
          0   SORT JOIN (cr=0 pr=0 pw=0 time=0 us)
          0    FIXED TABLE FULL X$KTADM (cr=0 pr=0 pw=0 time=0 us)
    Elapsed times include waiting on following events:
      Event waited on                             Times   Max. Wait  Total Waited
      ----------------------------------------   Waited  ----------  ------------
      SQL*Net message to client                       1        0.00          0.00
      buffer busy waits                              34        0.97         32.83
      SQL*Net break/reset to client                   1        0.00          0.00
    OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.00       0.00          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch        1      0.03      32.86          0          0          6           0
    total        3      0.03      32.86          0          0          6           0
    Misses in library cache during parse: 1
    Elapsed times include waiting on following events:
      Event waited on                             Times   Max. Wait  Total Waited
      ----------------------------------------   Waited  ----------  ------------
      SQL*Net message to client                       2        0.00          0.00
      SQL*Net message from client                     1       19.00         19.00
      buffer busy waits                              34        0.97         32.83
      SQL*Net break/reset to client                   1        0.00          0.00
    OVERALL TOTALS FOR ALL RECURSIVE STATEMENTS
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        0      0.00       0.00          0          0          0           0
    Execute      0      0.00       0.00          0          0          0           0
    Fetch        0      0.00       0.00          0          0          0           0
    total        0      0.00       0.00          0          0          0           0
    Misses in library cache during parse: 0
        1  user  SQL statements in session.
        0  internal SQL statements in session.
        1  SQL statements in session.
    Trace file: 502_ora_28260.trc
    Trace file compatibility: 10.01.00
    Sort options: default
           0  session in tracefile.
           1  user  SQL statements in trace file.
           0  internal SQL statements in trace file.
           1  SQL statements in trace file.
           1  unique SQL statements in trace file.
          64  lines in trace file.
          32  elapsed seconds in trace file. There is nothing fishy in alert logs... Please guide
    Thanks

    There it is TOP
    $ RUMPSHAKER>top
    load averages:  6.63,  7.45,  7.88;                    up 33+12:02:33           
    3631 processes: 3616 sleeping, 5 zombie, 1 stopped, 9 on cpu
    CPU states: 58.6% idle, 18.2% user, 23.2% kernel,  0.0% iowait,  0.0% swap
    Memory: 192G phys mem, 92G free mem, 96G swap, 96G free swap
       PID USERNAME LWP PRI NICE  SIZE   RES STATE    TIME    CPU COMMAND
    13752 ora0005    1  19    0 4243M 4219M sleep    5:21 62.78% oracle
    17758 ora0005    1  25    0 1174M 1156M cpu      1:05 37.12% oracle
    17923 root       1  57    0   18M   14M sleep  689:07 13.59% ecap_monitor
    20777 root      12  58    0   14M   13M sleep  864:33 11.55% OracleAgent
    18884 ora0004    1   1    0  830M  813M sleep    0:01  9.54% oracle
    12070 ora0004   61  58    0  320M  315M sleep   28.5H  8.29% emagent
    20347 root      16  59    0   33M   25M sleep   26.0H  6.34% caiUxsA2
    17949 ist0005    1  53    0 7984K 4984K cpu      0:00  3.93% top
         1 root       1  59    0 2912K 1288K sleep   32.2H  3.75% init
    15035 ora0001    1  46    0   32M   22M sleep  166:43  2.98% tnslsnr
      5748 ora0004   11  54    0  516M  496M sleep  389:37  2.78% oracle
    20567 ora0004    1  55    0   27M   22M sleep    0:00  2.69% sqlplus
      6730 ora0001    1  33    0  632M  616M sleep    0:06  2.67% oracle
    20557 ora0004    1  56    0   27M   23M sleep    0:00  2.53% sqlplus
      5355 ora0005    1  59    0 1154M 1137M sleep    0:04  2.46% oracleand VMSTAT 2 5
    $ RUMPSHAKER> vmstat 2 5
    kthr      memory            page            disk          faults      cpu
    r b w   swap  free  re  mf pi po fr de sr s0 s1 s2 sd   in   sy   cs us sy id
    6 8 0 143125576 74272080 4628 24012 488 150 149 0 0 4 4 -2 0 25037 192698 65249 38 26 36
    1 3 0 162803992 95246464 1989 6989 0 4 4 0 0 6 6 0  0 9170 57822 26434 8 13 79
    1 7 0 162801352 95240296 3043 15633 4 9737 9682 0 0 0 0 0 0 11277 73516 38200 16 16 68
    3 10 0 162801560 95227920 3326 12729 16 16862 16774 0 0 1 1 0 0 11377 86054 44758 16 17 68
    1 10 0 162784520 95186488 9638 48359 24 11682 11626 0 0 13 13 0 0 13484 149366 44205 23 29 47

  • Sorting Methods for an Array

    I'm trying to sort an object array of bank accounts based on their balance. JGRASP doesn't like my calling statement, which I don't think is correct.
    My question is am I calling the method correctly (trying to set the bankArray[counter].getBalance()) and am I using the sort method correctly?
    my call method
    bankArray = bankArray[counter].selectionSort(bankArray[counter].getBalance(), counter);My sort method:
    public static void selectionSort (double [] sort, int length)
    for (int i = length; i < 1; i--)
    double currentMax;
    int currentMaxIndex;
    currentMax = sort[0];
    currentMaxIndex = 0;
    for (int j = 1; j < i; j++)
    if (currentMax < sort[j])
    currentMax = sort[j];
    currentMaxIndex = j;
    }//End if
    }//End for

    There are some points to notice:
    Point 1: Your method receive an array of double and an int, as you passing a double and an int.
    Point 2: Your algorithm doesn't work properly. First of all, the selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping it with the item in the next position to be filled. Also, note that you don't swap the array elements in any moment.
    Point 3: In Java, your selectionSort method don't need to receive a parameter to inform the array length. The array itself already have that information ("myArray.length").
    Point 4: About the call of your method, you made it as the selectionSort method returns an array of BankAccounts - Supposing that you represent a bank account through an BankAccount class and bankArray[i] is an array of [i]BankAccount objects. It's not true. As you can see, your selectionSort method returns void, or either, returns nothing.
    Observing those 4 first points, we can re-write your selectionSort method like this
         public static void selectionSort(double[] numbers) {
                for (int i = 0; i < numbers.length - 1; i++)
                  int minIndex = i;
                  for (int j = i + 1; j < numbers.length; j++)
                    if (numbers[j] < numbers[minIndex])
                      minIndex = j;
                  double temp = numbers;
              numbers[i] = numbers[minIndex];
              numbers[minIndex] = temp;
    Now, when I try to re-write the call, I noticed other important odd thing about your approach: The [i]selectionSort method was written to sort bankAccounts, but it receives an array of double values. Being thus, you must to previously create a double[] object filled with the accounts' balances and then sort it. But, once sorted, how can you return the balances to their proper account? There is no way to do it. You have to sort a bunch of BankAccount objects, instead of an array of balances...
    An intuitive implementation of this sorting cound be something like that:     public static void selectionSort(BankAccount[] accounts) {
              for (int i = 0; i < accounts.length - 1; i++) {
                   int minIndex = i;
                   for (int j = i + 1; j < accounts.length; j++) {
                        double
                             currBalance = accounts[j].getBalance(),
                             minBalance = accounts[minIndex].getBalance()                    
                        if (currBalance < minBalance)
                             minIndex = j;
                   BankAccount temp = accounts;
                   accounts[i] = accounts[minIndex];
                   accounts[minIndex] = temp;
    I noticed form your call that the [i]selectionSort method boleng to the BankAccount class. Once this method is static, It's strongly recomended that you invoke this method in a static way (from the class, instead of from an object).
    Here it goes a fictional BankAccount class and a TestBankAccount class. Read it, Run it, Study it, Understand it.
    package help.sun.imbrium;
    public class BankAccount {
         private double balance;
         private int number;
         public static void selectionSort(BankAccount[] accounts) {
              for (int i = 0; i < accounts.length - 1; i++) {
                   int minIndex = i;
                   for (int j = i + 1; j < accounts.length; j++) {
                        double
                             currBalance = accounts[j].getBalance(),
                             minBalance = accounts[minIndex].getBalance()                    
                        if (currBalance < minBalance)
                             minIndex = j;
                   BankAccount temp = accounts;
                   accounts[i] = accounts[minIndex];
                   accounts[minIndex] = temp;
         public BankAccount(int number, double balance) {
              this.balance = balance;
              this.number = number;
         public double getBalance() {
              return balance;
         public void setBalance(double balance) {
              this.balance = balance;
         public int getNumber() {
              return number;
         public void setNumber(int number) {
              this.number = number;
         public String toString(){
              return "[Account #" + number + " balance: $" + balance + "]";
    class TestBankAccount{
         public static void main(String[] args) {
              BankAccount[] accounts = {
                   new BankAccount(1, 154.23),
                   new BankAccount(2, 1554.23),
                   new BankAccount(3, 15.3),
                   new BankAccount(4, 854),
                   new BankAccount(5, -4.79),
              System.out.println("Unsorted:\n\t" + arrayToString(accounts, " "));
              BankAccount.selectionSort(accounts);
              System.out.println("Sorted:\n\t" + arrayToString(accounts, " "));
         private static String arrayToString(Object[] objs, String separator){
              StringBuilder sb = new StringBuilder();
              for (int i = 0; i < objs.length; i++) {
                   Object obj = objs[i];
                   sb.append(obj.toString());
                   if(i < objs.length - 1)
                        sb.append(separator);
              return sb.toString();

  • Selection Sort troubles

    I am doing a practice exercise involving a Selection Sort. I keep getting 2 errors when I compile and not sure what to do to fix them. Thanks in advance for your help! Here are the two errors:
    SortArray.java:79: illegal start of expression
         private void swapEm ( int indexCheck, int min ){
            ^
    SortArray.java:67: cannot resolve symbol
    symbol  : method swapEm  (int,int)
    location: class SortArray
               swapEm( indexCheck, min );
                     ^Here is my code:
    import java.lang.Math.*;
    public class SortArray {
         * Main method for program.
         * @param  args
        public static void main ( String args[] ){
         int array[] = new int [25]; //variable for array
          * For loop to populate the array with numbers ranging
          * from 0-100 inclusively and then
          * printing them out on the screen.
         for ( int index = 0; index < array.length; index ++ ){
             array[index] =( ( int ) ( Math.random() * 101 )  );
             System.out.println( array[index] );
          * For loop that iterates through array and sorts the array
          * in ascending order.
         int min;
         for ( int indexCheck = 0; indexCheck <  array.length -1;
               indexCheck ++ ){
             min = indexCheck;
             for ( int index = indexCheck + 1; index < array.length;
               index ++ ){
              if ( array[index] < min ){
                   min = array[index];
               swapEm( indexCheck, min );
          * Swaps the values of the array to put them in order.
          * @param one a value of type 'int'
          * @param two a value of type 'int'
         private void swapEm ( int indexCheck, int min ){
             int temp = array[indexCheck];
             array[indexCheck] = array[min];
             array[min] = temp;
         System.out.println();
         for ( int intCounter = 0; intCounter < array.length;
               intCounter ++ ){
             System.out.println( array[intCounter] );
    }//SortArray.java

    This is how i would do it:
    for ( int index = 0; index < array.length; index ++ ){
                   array[index] =( ( int ) ( Math.random() * 101 )  );
                   System.out.println( array[index] );
              System.out.println("-----------");
              /* To sort the array in ascending order
              for (int i=0; i<25; i++) {
                   for (int j=i+1; j<25; j++) {
                        if (array[i] > array [j]) {
                             int temp = array;
                             array[i] = array [j];
                             array[j] = temp;
              for (int i=0; i<25; i++)
                   System.out.println ("" + array[i]);
    All inside your main() method, without even using other methods.
    Calin

  • AAAGGGHH!!! Selection sort with external file!

    Hi, i am trying to sort marks from an external file in ascending order, using a selection sort via an existing class StudentMark.
    However, i am receiving 1 error when i compile it!!!!
    code below:
    import java.io.*;
    import java.util.*;
    class sort
         // method to display the contents of an array
         static StudentMark data[];
         static void displayData(int[] data)
              try
                   data = StudentMark.loadMarks();
                   for (int index=0; index != data.length; index++)
                        System.out.println(data[index]+"\t");
              catch(Exception e)
                   System.out.println(e.getMessage());
         static int positionOfLargest(int[] data, int limit)
         // method to return the position of the largest item
         // in the data with bounds 0..limit
              int largest = data[0];
              int indexOfLargest = 0;
              for (int index=1; index <= limit; index++)
                   if (data[index]> largest)
                        largest = data[index];
                        indexOfLargest = index;
              return indexOfLargest;
         public static void selectionSort(int[] data)
         // method to sort the contents of an data into ascending order
              int temporary;
              int position;
              int size=data.length;
              for (int index=size-1; index > 0; index--)
                   position=positionOfLargest(data, index);
                   // swap numbers
                   if (index != position)
                        temporary = data[index];
                        data[index] = data[position];
                        data[position] = temporary;
         public static void main(String[] args)
              int[] data;
              System.out.println("numbers before being sorted\n");
              displayData(data);
              selectionSort(data);
              System.out.println("numbers after being sorted\n");
              displayData(data);
    the error is: sort.java:14: incompatible types -                data = StudentMark.loadMarks();
    ^
    Can anyone see what i am doing wrong??
    Thanks!!

    static StudentMark data[];
    data = StudentMark.loadMarks();the error message "incompatible types" means that the type of data and the return type of StudenMark.loadMarks() are not compatible.
    in case of we don't know the return type of StudentMark.loadMarks() i could only guess:
    class StudentMark {
      public static StudentMark[] loadMarks() {
    }if you used that kind of method declaration you should change your declatation of the variable data:
    public static StudentMark[] data;then your codeline 14 shouldn't be a problem any longer.
    StudentMark[] data and StudentMark data[] ARE different!
    hope it helps.

  • Recursive selection sort stack overflow

    hi, first time posting here.
    i have to write a java method that implements a selection sort. This method must be recursive. ok not a problem. i have come up with this so far
        public int findMin(int index) {
            int min = index - 1;
            if (index < num.length - 1) min = findMin(index + 1);
            if (num[index] < num[min]) min = index;
            return min;
        public void selectionSort(int left) {
            if (left < num.length - 1) {
                swap(left, findMin(left));
                selectionSort(left + 1);
        public void swap(int index1, int index2) {
            int temp = num[index1];
            num[index1] = num[index2];
            num[index2] = temp;
        }which works fine until i toss in a lot of values into the array. this creates a stack overflow, and ive been told that i need to use the divide and conquer method of resolving this issue. I guess this means to split the array up and sort each half seperatly, again and agin, or so im told.
    My question is how do i go about doing this, i am at a loss. Any help at all would be great.
    thank you
    lance

    i get this when i push the array passed about 5500 in sizeI got no problem. Post a small demo code that is generally compilable, runnable and could reproduce your problem. See: http://homepage1.nifty.com/algafield/sscce.html and http://www.yoda.arachsys.com/java/newsgroups.html
    It is silly to implement selection sort with recursion, double-silly if you use double-recursion as your current code.
    /* silly but no OOME when used against 5500 element array */
    import java.util.*;
    public class RecursiveSelectionSort{
      static int[] num;
      public static int findMin(int index) {
        int min = index; // your code had a bug here
        if (index < num.length - 1){
          min = findMin(index + 1);
        if (num[index] < num[min]){
          min = index;
        return min;
      public static void selectionSort(int left) {
        if (left < num.length - 1) {
          swap(left, findMin(left));
          selectionSort(left + 1);
      public static void swap(int index1, int index2) {
        int temp = num[index1];
        num[index1] = num[index2];
        num[index2] = temp;
      public static void main(String[] args){
        Random rand = new Random();
        int n = 10;
        if (args.length > 0){
          n = Integer.parseInt(args[0]);
        num = new int[n];
        for (int i = 0; i < num.length; ++i){
          num[i] = rand.nextInt(10000);
        selectionSort(0);
        for (int in : num){
          System.out.print(in + " ");
        System.out.println();
    }

  • Can someone please tell me a simple but effective method for burning a slideshow to DVD? Now that the connection between iPhoto and iDVD no longer exists, I can't figure out a way to get there with an acceptable quality result.

    Can someone please tell me a simple but effective method for burning a slideshow to DVD? Now that the connection between iPhoto and iDVD no longer exists, I can't figure out a way to get there with an acceptable quality result.

    Export the slideshow out of iPhoto as a QT movie file via the Export button in the lower toolbar.  Select Size = Medium or Large.
    Open iDVD, select a theme and drag the exported QT movie file into the open iDVD window being careful to avoid any drop zones.
    Follow this workflow to help assure the best qualty video DVD:
    Once you have the project as you want it save it as a disk image via the File ➙ Save as Disk Image  menu option. This will separate the encoding process from the burn process. 
    To check the encoding mount the disk image, launch DVD Player and play it.  If it plays OK with DVD Player the encoding is good.
    Then burn to disk with Disk Utility or Toast at the slowest speed available (2x-4x) to assure the best burn quality.  Always use top quality media:  Verbatim, Maxell or Taiyo Yuden DVD-R are the most recommended in these forums.
    If iDVD was not preinstalled on your Mac you'll have to obtain it by purchasing a copy of the iLife 09 disk from a 3rd party retailier like Amazon.com: ilife 09: Software or eBay.com.  Why, because iDVD (and iWeb) was discontinued by Apple over a year ago. 
    Why iLife 09 instead of 11?
    If you have to purchase an iLife disc in order to obtain the iDVD application remember that the iLife 11 disc only provides  themes from iDVD 5-7.  The Software Update no longer installs the earlier themes when starting from the iLIfe 11 disk nor do any of the iDVD 7 updaters available from the Apple Downloads website contain them. 
    Currently the only sure fire way to get all themes is to start with the iLife 09 disc:
    This shows the iDVD contents in the iLife 09 disc via Pacifist:
    You then can upgrade from iDVD 7.0.3 to iDVD 7.1.2 via the updaters at the Apple Downloads webpage.
    OT

  • Simple Select on VBPA using index running very slow

    Hello,
    We have a very simple selection on the table VBPA:
    data:
    begin of it_vbeln occurs 100,
      vbeln like vbpa-vbeln,
    end of it_vbeln.
    select vbeln from vbpa
    into table it_vbeln
    where
    kunnr = '##########'
    and parvw = 'AG'.
    All we're trying to accomplish is to find orders for a given customer number and type.
    We have two indices "Z1" and "Z2" which respectively declare: KUNNR, and MANDT, KUNNR, PARVW.
    In looking at a sql trace, it says it's using the VBPA~Z2 index, which is expected, and that its estimated costs are very low on the index:
    SELECT STATEMENT ( Estimated Costs = 71 , Estimated #Rows = 63 )
           2 TABLE ACCESS BY INDEX ROWID VBPA
             ( Estim. Costs = 71 , Estim. #Rows = 63 )
             Estim. CPU-Costs = 553,782 Estim. IO-Costs = 71
               1 INDEX RANGE SCAN VBPA~Z2
                 ( Estim. Costs = 3 , Estim. #Rows = 111 )
                 Search Columns: 3
                 Estim. CPU-Costs = 43,764 Estim. IO-Costs = 3
    Despite declaring that it will do an index range scan, in SM51 it shows as Sequential Read (Table Scan?) and takes a VERY long time to return, about 60 - 120 seconds.
    Since this is needed for a user exit that will be run during order creation, it needs to occur MUCH faster. Our entries in VBPA number above 10 million records currently.
    Can anyone suggest either why the index does not appear to be helping (it takes just as long without the index), or perhaps another method for finding the orders for a given customer number.
    Thank you,
    Randy

    Hi Randy,
    I suggest you skip the attempts to speed up selecting on VBPA, but rather look into using table VAKPA for finding sales documents for a given partner number.
    Greetings
    Thomas

  • Simple select query is taking a lot of time

    hi gems...
    my table has 7267563 rows...and i am doing a simple select * from table;
    but it is taking a lot of time nearly 25minutes but not completed...
    when i did select count(1) from table then it gave the result instantly also select * from table where rownum < 10 is also fine...even when i am selecting all the records using rownum i.e. select * from table where rownum < 7267563 is also giving result instantly...
    but the entire table is not getting result i.e. select * from table...also there is no lock in the table(though i know that select is nothing to do with lock)..
    what may be the issue..please suggest...thanks in advance...
    Edited by: user12780416 on Dec 12, 2011 11:08 PM

    Hi;
    Please see below thread
    query takes too long ...
    help in solving long run query
    HOW TO: Post a SQL statement tuning request - template posting
    Hope it helps
    Regard
    Helios

Maybe you are looking for