水桶
// 假设所有的数字在[0-100)之间
int[] nums = { 2, 5, 12, 5, 7, 8, 4, 80 };// 建水桶
int[] bucket = new int[100];
// 1.装水桶
for (int num : nums) {
bucket[num]++;
}
// 2.装回去
int index = 0;
for (int i = 0; i < bucket.length; i++) {
for (int j = 0; j < bucket[i]; j++) {
nums[index++] = i;
}
}
// 3.打印
System.out.println(Arrays.toString(nums));
----------------------------------------------------
冒泡
int[] nums={1,23,5,4,6};
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] > nums[j]) {
//方法一:用第三个变量换位置
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
方法二: 就用2个变量换位置
nums[i]=nums[i]+nums[j];
nums[j]=nums[i]-nums[j];
nums[i]=nums[i]-nums[j];
}
}
}