Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selection Sort not sorting in Java

Tags:

java

sorting

I'm sorry if I am asking too many questions hopefully I will be able to help out on this site. I'm trying to create a selection sort, but no luck in the sorting aspect.

import java.util.Random;

public class Tester {
public static void main(String[] args) {
selectionSort(args);
}

private static void printArray(int[] anArray) {
    for (int i = 0; i < anArray.length; i++) {
       if (i > 0) {
          System.out.print(", ");
       }
       System.out.print(anArray[i]);
    }
 }

public static void selectionSort(String[] args) {

    int i,n = 0,x = 0;

    int l = 10;
    int temp;
    Random r = new Random();
    int array[] = new int[l];
    for(i = 0;i < l; i++){
        array[i] = r.nextInt(271);
    }

    printArray(array);
    while(n < l){

         for(int j=0; j<l; j++){
             if(array[j] < array[x])
                x = j;

        }
        temp = array[x];
        array[x] = array[n];
        array[n] = temp;
        n++;
        x = n;
     }
     printArray(array);
    }

}

I think most of my problems are coming from

     for(int j=0; j<l; j++){
         if(array[j] < array[x])
          x = j;

        }
        temp = array[x];
        array[x] = array[n];
        array[n] = temp;
        n++;
        x = n;
     }

I couldn't figure this bottom out. I can get the smallest digit sorted, but then it is in an odd order. I figured the x changed constantly and I needed to keep it in order so I had it equal n. After that not working I am at a loss. I appreciate the help.

like image 761
DataStructors23 Avatar asked Nov 23 '25 08:11

DataStructors23


1 Answers

You did the loop section incorrectly, so do this:

 for(int j=0; j<l; j++){
    if(array[j] < array[x])
        x = j;

 }

instead of this:

for(int j=x+1; j<l; j++)
    if(array[j] < array[x])
        x = j;

Notice that each loop of the selection sort should start from the next of last element which is done its part.

like image 182
TomN Avatar answered Nov 24 '25 23:11

TomN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!