vendredi 27 mars 2015

Bubble sort isn't sorting properly



So, in my program, I am trying to take an array filled with random numbers and sort them using bubble sort. When I run my program I can clearly see the randomly generated numbers before the sorting begins, but after I run my bubbleSort method, the numbers are all 0's.


I'm sure there is something small I am overlooking but this is driving me crazy! Any suggestions would be appreciated. Thank you in advance!



import java.util.Random;
import java.util.Scanner;


public class partThree {

public static void main(String[] args) {

Scanner scan = new Scanner (System.in);
Random rand = new Random();

int max = 1000;

System.out.println("How many items are in the array? ");
int n = scan.nextInt();
int array[] = new int[n];

System.out.println("How many times should the loop be iterated? ");
int num_i = scan.nextInt();

rand.nextInt(max);

for(int i=0; i<num_i; i++)
array[i] = rand.nextInt(max);

System.out.println("Before sorting: ");
for(int i=0; i<num_i; i++){
System.out.println(array[i]);
}

bubbleSort(array);
System.out.println();

System.out.println("After sorting: ");
for(int i=0; i<num_i; i++){
System.out.println(array[i]);
}

}

public static void bubbleSort(int[] array){

int n = array.length;
int temp = 0;

for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){

if(array[j-1] > array[j]){
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}

}
}

}
}



Aucun commentaire:

Enregistrer un commentaire