使用布尔值对冒泡进行排序,以确定数组是否已经排序 [英] bubble sort with a boolean to determine whether array is already sorted
本文介绍了使用布尔值对冒泡进行排序,以确定数组是否已经排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码用于冒泡排序,但它根本没有排序。如果我删除我的布尔值然后它的工作正常。我明白,因为我的[0]比所有其他元素都要小,所以没有任何交换可以帮助我。
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;
}
}
推荐答案
您的冒泡冒错了?
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;
}
这篇关于使用布尔值对冒泡进行排序,以确定数组是否已经排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文