题目
输入n个数(n<=100),将其中的奇数从小到大排列,然后输出
Java实现
这里用的是快速排序,可自行选择其他排序
public static void test06(){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n > 100 || n < 1) return;
int[] a = new int[n];
for (int i = 0; i < n; i++) {
int input = sc.nextInt();
if (input % 2 != 0) a[i] = input;
}
sort(a,0,a.length-1);
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) System.out.print(a[i]+" ");
}
}
快速排序代码
public static int qSort(int[] a,int left,int right,int compare){
if (left == right) return left;
if (a[left] > compare || a[right] < compare){
int swap = a[right];
a[right] = a[left];
a[left] = swap;
}
if (a[left] == compare){
return qSort(a,left,--right,compare);
}else {
return qSort(a,++left,right,compare);
}
}
public static void sort(int[] a,int left,int right){
if (left < right){
int mid = qSort(a,left,right,a[left]);
sort(a,left,mid-1);
sort(a,mid+1,right);
}
}