/**
* @ClassName: SortArray
* @Description: 数组排序
* @Author: DiTian
* @Date: 2021/8/1 11:58
*/
public class SortArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个数组,以逗号分割:");
String s = scanner.nextLine();
String[] split = s.split(",");
int[] nums = new int[split.length];
for (int i = 0; i < split.length; i++) {
nums[i] = Integer.parseInt(split[i]);
}
//计数排序
long startTime = System.currentTimeMillis();
int[] a = countSort(nums);
long endTime = System.currentTimeMillis();
System.out.println("用时"+(endTime-startTime)+":"+Arrays.toString(a));
//快速排序
long startTime1 = System.currentTimeMillis();
quickSort(nums,0,nums.length-1);
long endTime1 = System.currentTimeMillis();
System.out.println("用时"+(endTime1-startTime1)+":"+Arrays.toString(nums));
}
private static void quickSort(int[] nums, int start, int end) {
int i,j,temp,t;
if (start>end){
return;
}
i = start;
j = end;
//temp是基准位
temp = nums[start];
while (i<j){
//先看右边,依次往左递减
while (i<j&&nums[j]>=temp){
j--;
}
//再看左边,依次往右递增
while (i<j&&nums[i]<=temp){
i++;
}
//如果满足条件,则交换
if (i<j){
t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
nums[start] = nums[i];
nums[i] = temp;
quickSort(nums,start,j-1);
quickSort(nums,j+1,end);
}
private static int[] countSort(int[] nums) {
int max = -1000,min = 1000;
for (int num : nums) {
max = Math.max(num,max);
min = Math.min(num,min);
}
int[] counter = new int[max-min+1];
for (int num : nums) {
counter[num-min]++;
}
int index = 0;
for (int num = min; num <= max ; num++) {
int c = counter[num-min];
while (c-- >0){
nums[index++] = num;
}
}
return nums;
}
}
快速排序和计数排序
最新推荐文章于 2022-03-28 18:35:42 发布