问题
I have following code for bubble sort but its not sorting at all. if I remove my boolean then its working fine. I understand that since my a[0] is lesser than all other elements therefore no swapping is being performed can anybody help me with this.
package com.sample;
public class BubleSort {
public static void main(String[] args) {
int a[] = { 1, 2, 4, 5, 6, 88, 4, 2, 4, 5, 8 };
a = sortBuble(a);
for (int i : a) {
System.out.println(i);
}
}
private static int[] sortBuble(int[] a) {
boolean swapped = true;
for (int i = 0; i < a.length && swapped; i++) {
swapped = false;
System.out.println("number of iteration" + i);
for (int j = i+1; j < a.length; j++) {
if (a[i] > a[j]) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
swapped = true;
}
}
}
return a;
}
}
回答1:
Your bubble sort is wrong?
private static int[] sortBuble(int[] a) {
boolean swapped = true;
int n = a.length;
for (int i = 0; i < n && swapped; i++) {
swapped = false;
int newn = 0;
System.out.println("number of iteration" + i);
for (int j = 1; j < a.length; j++) {
if (a[j-1] > a[j]) {
int temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
swapped = true;
newn = j;
}
}
n = newn;
}
return a;
}
回答2:
This is essentially the same as yours, but working and more efficient:
private static int[] bubblesort(int[] nums)
{
boolean done = false;
for (int i = 0; i < nums.length && !done; i++)
{
done = true;
for (int j = nums.length-1; j > i; j--)
{
if (nums[j] < nums[j-1])
{
int temp = nums[j];
nums[j] = nums[j-1];
nums[j-1] = temp;
done = false;
}
}
}
return nums;
}
At the end of the ith iteration, we know that the first i elements are sorted, so we don't need to look at them anymore. We need the boolean to determine if we need to continue or not. If no swaps are made, then we are done. We can remove the boolean and it will still work, but will be less efficient.
回答3:
It is called flagged bubble sort. It helps to save time mainly. It checks whether the array positions are sorted. if it is sorted it breaks, and move to 2nd execution.
and the code can be rewritten as:-
for (int j = 1; j < a.length; j++) {
if (a[j-1] > a[j]) {
int temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
swapped = true;
}
}
if(!swapped)
break;
}
来源:https://stackoverflow.com/questions/19886984/bubble-sort-with-a-boolean-to-determine-whether-array-is-already-sorted