为什么我的打印输出数组未在以下代码中排序?
public class BubbleSort { public void sortArray(int[] x) {//go through the array and sort from smallest to highest 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; } } } public void printArray(int[] x) { for(int i=0; i<x.length; i++) System.out.print(x[i] + " "); } public static void main(String[] args) { // TestBubbleSort BubbleSort b = new BubbleSort(); int[] num = {5,4,3,2,1}; b.sortArray(num); b.printArray(num); } }
您需要两个循环来实现Bubble Sort。
样例代码:
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; } } } }