The main method creates an array of random integers then calls the ascending and descending methods to sort the array. It seems that when I call the ascending and descending methods it alters the value of the original array. The output I receive when printing is three arrays all sorted in descending order.
public static void main(String[] args){
Random random = new Random();
Scanner myScan = new Scanner(System.in);
System.out.println("How many random numbers should be created?");
int size = myScan.nextInt();
int[] array = new int[size];
for(int i = 0; i<array.length; i++){
array[i] = random.nextInt(256);
}
int[] ascending = BubbleSort.ascending(array);
int[] descending = BubbleSort.descending(array);
System.out.print("Original array: ");
for(int i = 0; i< array.length; i++){
System.out.print(array[i] + " ");
}
System.out.println();
System.out.print("Array in ascending order: ");
for(int i =0; i< ascending.length; i++){
System.out.print(ascending[i] + " ");
}
System.out.println();
System.out.print("Array in descending order: ");
for(int i = 0; i<descending.length; i++){
System.out.print(descending[i] + " ");
}
System.out.println();
}
Here are the two sorting methods.
public static int[] ascending(int[] a){
int temp;
for(int i = 0; i < a.length - 1; i++){
for(int j = 0; j < a.length - 1; j++){
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
return(a);
}
public static int[] descending(int[] b){
int temp;
for(int i = 0; i < b.length - 1; i++){
for(int j = 0; j < b.length -1; j++){
if(b[j] < b[j+1]){
temp = b[j];
b[j] = b[j+1];
b[j+1] = temp;
}
}
}
return(b);
}
Instead of
int[] ascending = BubbleSort.ascending(array);
I thought to try
int[] ascending = new int[array.length];
ascending = BubbleSort.ascending(array);
But I receive the same results. Sorry for being such a programming newbie, and thanks for any guidance!