java冒泡法排序代码
//Sorts an integer array in ascending order. //Parameters: // data - reference to the integer array to sort, must not be null //Postcondition: // The array is sorted in ascending order. public static void bubbleSort(int[] data) { for (int k = 0; k < data.length - 1; k++) { boolean isSorted = true; for (int i = 1; i < data.length - k; i++) { if (data[i] < data[i - 1]) { int tempVariable = data[i]; data[i] = data[i - 1]; data[i - 1] = tempVariable; isSorted = false; } } if (isSorted) break; } }
代码2
// another possibility static int[] BubbleSort(int[] nums) { boolean unsorted = true; while (unsorted) { unsorted = false; for (int i = nums.length - 1; i > 0; i--) { if (nums[i] < nums[i-1]) { int temp = nums[i]; nums[i] = nums[i-1]; nums[i-1] = temp; unsorted = true; } } } return nums; }