Sorting an Array of int using BubbleSort
You need two loops to implement the Bubble Sort .
Sample code :
public static void bubbleSort(int[] numArray) {
int n = numArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (numArray[j - 1] > numArray[j]) {
temp = numArray[j - 1];
numArray[j - 1] = numArray[j];
numArray[j] = temp;
}
}
}
}
You're only making one pass through your array! Bubble sort requires you to keep looping until you find that you are no longer doing any swapping; hence the running time of O(n^2).
Try this:
public void sortArray(int[] x) {
boolean swapped = true;
while (swapped) {
swapped = false;
for(int i=1; i<x.length; i++) {
int temp=0;
if(x[i-1] > x[i]) {
temp = x[i-1];
x[i-1] = x[i];
x[i] = temp;
swapped = true;
}
}
}
}
Once swapped == false
at the end of a loop, you have made a whole pass without finding any instances where x[i-1] > x[i]
and, hence, you know the array is sorted. Only then can you terminate the algorithm.
You can also replace the outer while
loop with a for loop of n+1
iterations, which will guarantee that the array is in order; however, the while
loop has the advantage of early termination in a better-than-worst-case scenario.
Your sort logic is wrong. This is the pseudo-code for bubble sort:
for i = 1:n,
swapped = false
for j = n:i+1,
if a[j] < a[j-1],
swap a[j,j-1]
swapped = true
→ invariant: a[1..i] in final position
break if not swapped
end
See this sorting web site for good tutorial on all the various sorting methods.
I use this method for bubble sorting
public static int[] bubbleSort (int[] a) {
int n = a.length;
int j = 0;
boolean swap = true;
while (swap) {
swap = false;
for (int j = 1; j < n; j++) {
if (a[j-1] > a[j]) {
j = a[j-1];
a[j-1] = a[j];
a[j] = j;
swap = true;
}
}
n = n - 1;
}
return a;
}//end bubbleSort