对于已知从小到大和从大到小的数,如何用while进行排序,这个有思路,但不知怎么代,
从你贴出来的代码来看,逻辑是输入一个4位数,然后对组成这个4位数的每个数字进行排序,归根到底就是一个排序问题,用while循环的话就可以使用快速排序
下面是代码
public void quickSort(int[] nums, int low, int high) {
if (low < high) {
int index = partition(nums, low, high);
quickSort(nums, low, index - 1);
quickSort(nums, index + 1, high);
}
}
public int partition(int[] nums, int low, int high) {
int pivot = nums[low];
int start = low;
while (low < high) {
// while (low < high && nums[high] <= pivot) // 从大到小
while (low < high && nums[high] >= pivot)
high--;
// while (low < high && nums[low] >= pivot) // 从大到小
while (low < high && nums[low] <= pivot)
low++;
if (low >= high)
break;
swap(nums, low, high);
}
//基准值归位
swap(nums, start, low);
return low;
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}