题解 | #输入整型数组和排序标识,对其元素按照升序或降序进行排序#
输入整型数组和排序标识,对其元素按照升序或降序进行排序
http://www.nowcoder.com/practice/dd0c6b26c9e541f5b935047ff4156309
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = Integer.valueOf(scan.nextLine().trim());
String line = scan.nextLine();
String[] strs = line.split(" ");
int[] nums = new int[strs.length];
for (int i = 0; i < nums.length; i++) {
nums[i] = Integer.valueOf(strs[i].trim());
}
int sign = Integer.valueOf(scan.nextLine().trim());
mergeSort(nums, sign);
for (int i = 0; i < nums.length; i++) {
if (i == nums.length - 1) {
System.out.print(nums[i]);
return;
}
System.out.print(nums[i] + " ");
}
}
public static void mergeSort(int[] nums, int sign) {
if (null == nums || nums.length < 2) {
return;
}
process(nums, 0, nums.length - 1, sign);
}
public static void process(int[] nums, int start, int end, int sign) {
if (start >= end) {
return;
}
int mid = start + ((end - start) >> 1);
process(nums, start, mid, sign);
process(nums, mid + 1, end, sign);
if (sign == 0) {
merge1(nums, start, mid, end);
} else {
merge2(nums, start, mid, end);
}
}
public static void merge1(int[] nums, int start, int mid, int end) {
int[] helper = new int[end - start + 1];
int index = 0;
int p1 = start;
int p2 = mid + 1;
while (p1 <= mid && p2 <= end) {
helper[index++] = nums[p1] <= nums[p2] ? nums[p1++] : nums[p2++];
}
while (p1 <= mid) {
helper[index++] = nums[p1++];
}
while (p2 <= end) {
helper[index++] = nums[p2++];
}
for (int i = 0; i < helper.length; i++) {
nums[start + i] = helper[i];
}
}
public static void merge2(int[] nums, int start, int mid, int end) {
int[] helper = new int[end - start + 1];
int index = 0;
int p1 = start;
int p2 = mid + 1;
while (p1 <= mid && p2 <= end) {
helper[index++] = nums[p1] >= nums[p2] ? nums[p1++] : nums[p2++];
}
while (p1 <= mid) {
helper[index++] = nums[p1++];
}
while (p2 <= end) {
helper[index++] = nums[p2++];
}
for (int i = 0; i < helper.length; i++) {
nums[start + i] = helper[i];
}
}
}