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>".

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!

  • Select Sorting in prompt level

    I have below requirement from user.
    Prompts:     Loan Id
              Loan Type
              Sort by Account Number/Sale Type
    Basically when user run the report, it should prompt below three fields.
    Loan Id
    Loan Type
    Sort order with a drop down list which has values Account Number/ Sale Type.
    i.e., user should be able to select sort order he wants for both Account Number/ Sale Type before running the report at
    prompt level.
    Does anyone know the best way to accomplish this?.
    Thanks,
    ven
    Edited by: Ven Men on Jan 21, 2009 8:32 PM

    Hi Deb,
    Thanks for your reply. I need little more clarification from you regarding Ascending/Descending and group by.
    Please see my comments below.
    1) Created a prompt at the universe level where users can choose their sorting option, ie. Ascending or Descending.
        How did you create this. What I did is I created a derived table in Universe with below code.
       "Select distinct table.Account_Number from table order by 1". It just does only Ascending.
       Then I created a prompt, called Sort_Order, in designer as 
       '1'!=@Prompt('Sort_Order','A',{'Account_Number'},mono,Not_Persistent))
      It is not parsed with a Parsing Result as Parse failed: Exception: DBD, ORA-00903: invalid table     name   State: N/A
    Since I am not taking this value from database table, I went ahead and created this prompt and exported universe.
      What I understood from your point is I need to create two different prompts, once for Ascending and one for Descending. Please
      let me know if I am going wrong.
    2) In the WebI report, create two variables, one for Ascending and Descending. The formulas would be something like:
       cv_Ascending: if(userresponse("Sort order prompt text here")="Ascending";MyField)
       cv_Descending: if(userresponse("Sort order prompt text here")="Descending";MyField)
       I created variable as Sort_Act_Num =if(UserResponse("Sort_Order") = "Account_Number"; [Account Number]; 0).  This just sorts in Ascending order only and when I want to change it to descending, it is not working.
    3) Put the cv_Ascending variable in column one set to sort ascending and put cv_Descending variable in column two set to sort descending. (The column with the value that isn't selected is always null so it's sorted on nothing)
    4) Since you can't really "hide" columns in WebI, you have to fake it. Set the font color to white (or whatever color your background is) and the width to zero (0) - unfortunately, it won't let you set it to 0, it will default to .02. Turn off the borders. The columns will in effect be "hidden" and disappear.
    I've done the same thing with grouping, by creating a variable and using it as a section break. Works like a charm.
    For grouping, do I need to create any prompts or variables in designer level? Also in report level, is the code same as above to create variable for grouping.
    Please let me know..
    Thanks,
    Ven Men

  • Select Sorting at prompt level

    Hi,
       How to select sorting parameter from prompt level?  I have followed the thread [Select Sorting in prompt level  |Re: Select Sorting in prompt level;. I got struck while creating " Prompt - Sort Order" object. How to do this?
    Regards,
    Malini.V

    Hi folks,
    I am a report designer and I use BOXI r2 sp4. After researching the boards, I asked my design team to create the Sort-Order prompt object at the universe level.
    From what I understood, they created it in an independent dervived table. I need to have it joined to another table that contains the "measures" but I don't know what kind of joins should be constructed.
    In the report, I'd like to use it for something like the following:
    >if(Prompt - Sort Order="Descending";cost of service)...
    I would greatly appreciate the advice of the SMEs on how to complete this requirement.
    Wannetta
    Edited by: Wannetta Thomas on May 18, 2009 7:49 PM

  • How to display the steps of a sort algorithm??

    I'm having a lot of trouble trying to display the results of applying a merge sort to a set of 10 integers. The problem is not that I can't see anything on the text area within the applet, the problem is that I am getting a lot of repetitions and duplicates occuring. I have tried inserting the Display() method in various positions in the sort, I have set up a temporary array to compare the elements of the array before and after the particular step of the sort is applied and an if statement to display only if there are changes have happened to the array. Can anyone advise?? Here's the code for the sort, including my current attempt to get the sort diplayed in steps:
    public class MSort extends JFrame
    public MSort(int[] anArray, JApplet anApplet)
    a = anArray;
    applet = anApplet;
    ArrayUtil.Display(a,textArea);
    JumpLine(textArea);
    Sorts the array managed by this merge sorter
    public void sort()
    throws InterruptedException
    mergeSort(0, a.length - 1);
    textArea.append("End of Merge Sort");
    Sorts a range of the array, using the merge sort
    algorithm.
    @param from the first index of the range to sort
    @param to the last index of the range to sort
    public void mergeSort(int from, int to)
    throws InterruptedException
    if (from == to) return;
    int mid = (from + to) / 2;
    mergeSort(from, mid);
    mergeSort(mid + 1, to);
    merge(from, mid, to);
    Merges two adjacent subranges of the array
    @param from the index of the first element of the
    first range
    @param mid the index of the last element of the
    first range
    @param to the index of the last element of the
    second range
    public void merge(int from, int mid, int to)
    throws InterruptedException
    startPosition = from;
    endPosition = to;
    int n = to - from + 1;
    // size of the range to be merged
    // merge both halves into a temporary array b
    int[] b = new int[n];
    int i1 = from;
    // next element to consider in the first range
    int i2 = mid + 1;
    // next element to consider in the second range
    int j = 0;
    // next open position in b
    int[] oldArray = new int[a.length];
    System.arraycopy(a, 0, oldArray, 0, oldArray.length);
    // as long as neither i1 nor i2 past the end, move
    // the smaller element into b
    while (i1 <= mid && i2 <= to)
    if (a[i1] < a[i2])
              b[j] = a[i1];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
    i1++;
    else
    b[j] = a[i2];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
    i2++;
         pause(2);
    j++;
         for (int k=0; k < a.length-1; k++) {// method I've put in to                  try and compare the array b4 and after the sort
    if (a[k] != oldArray[k]){
    ArrayUtil.Display(a,textArea);
    JumpLine(textArea);
    // note that only one of the two while loops
    // below is executed
    // copy any remaining entries of the first half
    while (i1 <= mid)
    b[j] = a[i1];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
    //ArrayUtil.Display(a,textArea);
                        //JumpLine(textArea);
    pause(2);
    i1++;
    j++;
    // copy any remaining entries of the second half
    while (i2 <= to)
    b[j] = a[i2];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
         } pause(2);
    i2++;
    j++;
    // copy back from the temporary array
    for (j = 0; j < n; j++)
    a[from + j] = b[j];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
    pause(2);
    public void pause(int steps)
    throws InterruptedException
    if (Thread.currentThread().isInterrupted())
    throw new InterruptedException();
    applet.repaint();
    Thread.sleep(steps * DELAY);
    private int[] a;
    private int startPosition = -1;
    private int endPosition = -1;
         private JTextArea textArea = SortApplet1.getTextArea2();
    private JApplet applet;
    private static final int DELAY = 100;
    public static void JumpLine(JTextArea t){
         JTextArea TxtArea = t;
         TxtArea.append("\n\n");
    }

    see sample at http://lwh.free.fr/pages/algo/tri/tri.htm
    marvinrouge

  • Hi how to find runtime for sorting algorithms

    I am new to java.......please help me out by taking a sorting algorithm and find the run time of it ......
    Thanks in Advance

    If by "runtime" you just mean the amount of time it takes to execute across some set of input...then you can use java.lang.System.currentTimeMillis() to get the current time in milliseconds since Jan 1 1970. Do that both before and after you run the code that implements the algorithm, and subtract to get the difference as running time in milliseconds. Or, if this weren't part of a homework assignment, you could just use a profiler.
    If by "runtime" you mean the execution environment, then you want to use java.lang.Runtime.getRuntime(). This has nothing to do with algorithms.
    If you mean that you want to analyze the efficiency of the algorithm (eg it's "big-O" notation), then read a textbook on algorithms. This has nothing to do with Java, apart from that Java is just one computer language out of many in which algorithms can be implemented.

  • [SOLVED] What is this sorting algorithm? (or a new one?)

    Hello everyone!
    Just before starting, i apologize for my grammar mistakes.
    I found a new sorting algorithm but i'm not sure if i really found it. There are too many sorting algorithms and mine is a really simple one; so, i belive that it can be found years ago.
    I searched popular sorting algorithms, but none of the them is the answer.
    Here is algorithm:
    * Search the numbers between brackets
    [24 12 12 55 64 18 32 31]
    * Find smallest one
    [24 12 12 55 64 18 32 31]
    ^S
    * Swap the first item between brackets with smallest one
    [12 12 24 55 64 18 32 31]
    * Find largest one
    [12 12 24 55 64 18 32 31]
    ^L
    * Swap the last item between brackets with largest one
    [12 12 24 55 31 18 32 64]
    * Move brackets by one.
    12[12 24 55 31 18 32]64
    * Continue from step one until the array is sorted
    /* rottsort
    Copyright (c) 2013 Bora M. Alper
    #include <stdio.h>
    void print_array (const int *array, const int length);
    int rottsort_swap (int *x, int *y);
    void rottsort (int *array, const int length);
    int rottsort_largest (const int *array, const int start, const int end);
    int rottsort_smallest (const int *array, const int start, const int end);
    void print_array (const int *array, const int length) {
    int i;
    for (i=0; i < length; ++i)
    printf ("%d ", array[i]);
    putchar ('\n');
    int main (void) {
    int array[] = {24, 12, 12, 55, 64, 18, 32, 31};
    print_array(array, 8);
    rottsort(array, 8);
    print_array(array, 8);
    return 0;
    int rottsort_swap (int *x, int *y) {
    const int temp = *x;
    *x = *y;
    *y = temp;
    void rottsort (int *array, const int length) {
    int i, largest_pos, smallest_pos;
    for (i=0; i < length/2; ++i) {
    largest_pos = rottsort_largest(array, i, length-1-i);
    rottsort_swap(&(array[largest_pos]), &(array[length-1-i]));
    smallest_pos = rottsort_smallest(array, i, length-1-i);
    rottsort_swap(&(array[smallest_pos]), &(array[i]));
    int rottsort_largest (const int *array, const int start, const int end) {
    int i, largest_pos = start;
    for (i=start; i <= end; ++i)
    if (array[i] >= array[largest_pos])
    largest_pos = i;
    return largest_pos;
    int rottsort_smallest (const int *array, const int start, const int end) {
    int i, smallest_pos = start;
    for (i=start; i <= end; ++i)
    if (array[i] <= array[smallest_pos])
    smallest_pos = i;
    return smallest_pos;
    P.S.: If this is a new sorting algorithm, i name it as "rottsort". :)
    Last edited by boraalper4 (2013-08-11 19:08:17)

    Trilby wrote:
    Because you already have two variables for largets and smallest, there is no reason to loop through the whole list twice to get each.  Loop through the list (or list subset) once, and in each loop check if the current item is smaller than smallest_pos or larger than largest_pos.
    This will increase efficiency by a factor of two.
    As written I believe it'd be less efficient than even a simple bubble sort.  With the above revision it may be comparable to a bubble sort.
    Thanks for quick answer and advice. :) I will try to do that. When i'm done, i will post the new code.
    Code is tested on codepad. (I edited the code on my phone so, sorry for formatting)
    /* rottsort
    Copyright (c) 2013 Bora M. Alper
    #include <stdio.h>
    void print_array (const int *array, const int length);
    int rottsort_swap (int *x, int *y);
    void rottsort (int *array, const int length);
    void rottsort_find (int *smallest_pos, int *largest_pos, const int *array, const int start, const int end);
    void print_array (const int *array, const int length) {
    int i;
    for (i=0; i < length; ++i)
    printf ("%d ", array[i]);
    putchar ('\n');
    int main (void) {
    int array[] = {24, 12, 12, 55, 64, 18, 32, 31};
    print_array(array, 8);
    rottsort(array, 8);
    print_array(array, 8);
    return 0;
    int rottsort_swap (int *x, int *y) {
    const int temp = *x;
    *x = *y;
    *y = temp;
    void rottsort (int *array, const int length) {
    int i, largest_pos, smallest_pos;
    for (i=0; i < length/2; ++i) {
    rottsort_find (&smallest_pos, &largest_pos, array, i, length-1-i);
    rottsort_swap(&(array[largest_pos]), &(array[length-1-i]));
    if (smallest_pos == length-1-i)
    smallest_pos = largest_pos;
    rottsort_swap(&(array[smallest_pos]), &(array[i]));
    void rottsort_find (int *smallest_pos, int *largest_pos, const int *array, const int start, const int end) {
    int i;
    *smallest_pos = start;
    *largest_pos = start;
    for (i=start; i <= end; ++i) {
    if (array[i] >= array[*largest_pos])
    *largest_pos = i;
    if (array[i] <= array[*smallest_pos])
    *smallest_pos = i;
    Last edited by boraalper4 (2013-08-11 15:21:48)

  • Radix sort algorithm

    You guys, I need a radix sort algorithm for java. I've worked on it for a while, and I cant get it. I have this so far:
    public void radixSort(int maxDigits)
              Vector temp = new Vector();
              int count = 1;
              while(count<(Math.pow(10,maxDigits)))
                   int c=0;
                   while(c<10)
                        for(int i=0;i<students.size();i++)
                             int per = ((MyStudent)students.elementAt(i)).getPercentage()/count;                         
                             if(per%10==count)
                                  temp.add((MyStudent)students.elementAt(i));
                        c++;
                   count*=10;
              students = temp;
    students is the main vector in the class, and percentage is the thing we are trying to sort. The accessor for percentage is (MyStudent)students.elementAt(i).getPercentage(). It has to be cast to (MyStudent) object.

    Sorry here is a formatted version of my question:
    You guys, I need a radix sort algorithm for java. I've worked on it for a while, and I cant get it. I have this so far:
    public void radixSort(int maxDigits)
              Vector temp = new Vector();
              int count = 1;
              while(count<(Math.pow(10,maxDigits)))
                   int c=0;
                   while(c<10)
                        for(int i=0;i<students.size();i++)
                             int per = ((MyStudent)students.elementAt(i)).getPercentage()/count;                         
                             if(per%10==count)
                                  temp.add((MyStudent)students.elementAt(i));
                        c++;
                   count*=10;
              students = temp;
         }students is the main vector in the class, and percentage is the thing we are trying to sort. The accessor for percentage is (MyStudent)students.elementAt(i).getPercentage(). It has to be cast to (MyStudent) object.

  • Quick-Sort Algorithm HELP !!!

    hi there, I wrote a method to sort an 2D-Vector. I used the Bubble-Algorithm.
    Here the code:
    Vector == [Micky, Niko, Tete] ; [Lilo, Eli, Micha];
    public static void bubbleSort( Vector v,
    int sortColumn,
    boolean ascending )
    int i = 0,
    j = 0,
    length = v.size();
    Vector tmp1,
    tmp2;
    for (i = 0; i < (length - 1); i++)
    for (j = i+1; j < length; j++)
    tmp1 = (Vector) v.elementAt(i);
    tmp2 = (Vector) v.elementAt(j);
    if (SortUtil.isGreaterThan(tmp1.elementAt(sortColumn), tmp2.elementAt(sortColumn)) > 0)
    // swap
    SortUtil.swap2D(v, i, j);
    public class SortUtil
    public static int isGreaterThan(Object obj1, Object2)
    // String
    if ( (obj1 instanceof String) && (obj2 instanceof String) )
    return ( ((String) obj1).compareTo((String) obj2) );
    public static void swap2D(Vector v, int i)
    Vector tmp = (Vector) v.elementAt(i);
    v.setElementAt((Vector) v.elementAt(i+1), i);
    v.setElementAt(tmp, i+1);
    I want now to write a method to use the quick-sort-algorithm.
    How can I do this.
    thanks a lot.
    micky z.

    Hi
    You can use java.util.Arrays.sort() method to sort an array of data in quick sort algo. May be you will have to use a n array insted of the Vector.
    Use vector.toArray() method to get an array from the vector.
    But if you want to use a dynamically resizing container like the Vector, use a java.util.LinkedList insted of the Vector and use Collections.sort() method
    Good luck.

  • Sorting algorithm ?

    what is the sorting algorithm used in Collection.sort ?
    Its not clear what sorting algorithm is used in Collection.sort
    http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html
    Can anybody throw some light on this ?

    roy wrote:
    It works on binary search algorithm.No.
    Binary search requires that the list already be sorted. You don't use binary search to do the sorting.
    This algorithm has two forms. The first takes a List and an element to search for (the "search key"). This form assumes that the List is sorted in ascending order according to the natural ordering of its elements. The second form takes a Comparator in addition to the List and the search key.The second form also assumes the list is sorted--according to the rules of the comparator.

  • Selection Sorting of Data type (Char)

    public class CharSortTest {
        public static void main(String[] args) {
            char[] letters = {'j', 'a', 'z', 'y', 'x'};
            char min = 0;
            char swap = 0;
            for (int x = 0; x <= letters.length - 1; x++) {
                min = letters[x];
                for (int i = x + 1; i <= letters.length - 1; i++) {
                    if (letters[i] < min) {
                        min = letters;
    if (letters[x] != min) {
    swap = letters[x];
    letters[x] = min;
    min = swap;
    for (int p = 0; p <= letters.length - 1; p++) {
    System.out.println(letters[p]);
    }output:a
    a
    x
    x
    xi followed the logic of selection sorting.. i even checked the integer values of each character in my array
    but why is my program not sorting                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    vajj wrote:
    public class CharSortTest {
    i followed the logic of selection sorting..Obviously you didn't.
    Put in print statements at each step so you can see exactly what's happening--varaibles' values, code paths being followed, etc.

  • 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

  • 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!

  • Comparable interface selection sort

    Hi,
    I've created a Person Class with a comparable interface. And i've created an ArrayList People with varaibles from the person class in - First_name, Surname, Month(Birthday), Day(Birthday).
    Now i need to use selection sort to sort my arraylist into birthday order. In the Person Class i have a method which gives each person a different number for every possible birthday there is.
    I have created a selction sort but dont know how to call the birthday from my array list and then to sort it.
    This is my code for the selection sort so far:
    import java.util.ArrayList.*;
    public class Main
    public static void selectionSort(Comparable[] people)
    for (int k = people.length-1; k>0; k --)
    Comparable tmp;
    int Large = 0;
    for (int j=1; j<= k; j++)
    if (people[j].compareTo(people[k]) <0)
    Large = j;
    tmp = people[Large];
    people[Large] = people[k];
    people[k] = tmp;
    this method compiles but i need to sort the birthday and dont know how. Also i need to output the whole array in birthday order.
    Any help would be very greatful.
    Thanks
    Dave

    Hi,
    If my understanding is right..
    You are trying to sort with birthday as the primary sort criterria.
    For doing that, you have to write the comparison logic inside the compareTo() method implemented in the Person class (Inherited from Comparable Interface).
    i.e. The compareTo() method should use the the primary_sort_variable(here it is birthday or something derived from it) to return a boolean value for your need.

  • 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.

Maybe you are looking for

  • Inverted grayscale images placed in Indesign

    I have customer files that were created in Indesign CS3 and CS4 with a placed, colored grayscale image on a colored background. The image is inverted but I cannot seem to replicate this. I know you can do this easily in Quark but how do you do this i

  • Report Painter - Display settings of variations

    Hi, In my report CO, I have a characteristic which is displayed as a variation. It's a set variable, let's says a group of profit centers (a set of multiple single sets). When execute the report, the value list of variation is always expand-all. It's

  • Error on creating Services in Hyperion planning configuration

    Hello Sir, Here I started Hyperion installation on Multiple Systems 1. fndserver I installed essbase, planning components, and I configured only foundation here, and eas installed and its working Web logic is application server 7001 port 2. essserver

  • Aligning text boxes

    I have a form that must be filled electronically and then printed there are 100 text boxes that will have one letter in each How can I get the 5 x 20 boxes to align so that they look like a grid rather then a bunch of slightly overlapping boxes?

  • Best way to handle cover for saddle-stitched book

    I have a small book (80 pages, including covers, 5.5 x 8.5 finished size) that will be saddle-stitched. I need to make a front and back cover that bleed together, so I figure the best way to do this is simply to create a new document with a single pa