最近在學(xué)習(xí)java,想練習(xí)一下編寫,使用了eclipse編寫了如下的排序代碼。其中包含了快速排序, 選擇排序,插入排序,冒泡排序。
/*
*
* Roc
*
* 2013/10/4
*
* 此段代碼主要是通過java來實(shí)現(xiàn)多種排序
*
*/
package Sorting;
import java.util.Scanner;
public class sorting {
//直接插入排序
static void InsertSort(int a[]){
for (int i = 1; i < a.length; i++){
int t = a[i];
int j = i;
while ((j > 0) && (a[j-1] > t)){
a[j] = a[j-1];
--j;
}
a[j] = t;
}
}
//快速排序
static void QuickSort(int a[], int low, int high){
int index[] = new int[2];//用于保存劃分方法返回的結(jié)果
if (low < high){
Partition(a, low, high, index);//劃分L[low..high]
QuickSort(a, low, index[0]);
QuickSort(a, index[1], high);
}
}
static void Partition(int a[], int p, int r, int ind[]){
int i, j, k, pivot;
pivot = a[(p+r)/2];
i = p;
j = p;
k = r;
while (j != k){
if (a[j] == pivot){
j++;
} else if (a[j] < pivot){
swap(a[j], a[i]);
j++;
i++;
} else {
swap(a[j], a[k-1]);
k--;
}
}
ind[0] = i;
ind[1] = j;
}
//用于整數(shù)之間進(jìn)行的交換
static void swap(int a, int b){
int temp;
temp = a;
a = b;
b = temp;
}
//選擇排序
static void SelectionSort(int a[]){
int min;
for (int j = 0; j < a.length-1; j++){
min = j;
for (int k = j+1; k < a.length; k++){
if (a[k] < a[min])
min = k;
}
swap(a[min], a[j]);
}
}
//冒泡排序
static void BubbleSort(int a[]){
for (int i = 0; i < a.length; i++){
for (int j = 0; j < a.length-i-1; j++){
if (a[j] > a[j+1])
swap(a[j], a[j+1]);
}
}
}
static void PrintThem(int a[]){
System.out.println("\nAfter sorted, they are: ");
for (int i = 0; i < a.length; i++)
System.out.print(a[i]+" ");
}
public static void main(String[] args){
int number1, number2;
int low, high;
Scanner reader = new Scanner(System.in);
System.out.print("How many numbers you want to sort: ");
number1 = reader.nextInt();
int a[] = new int[number1];
System.out.println("\nNow, input them here: ");
for (int i = 0; i < a.length; i++)
a[i] = reader.nextInt();
System.out.println("\t\tChose one of way to sort them: ");
System.out.println("\t1.Insert Sort \t 2.Quick Sort \t " +
"3.Select Sort \t 4.Bubble Sort \t 0.Abort");
System.out.print("Input your chose here: ");
number2 = reader.nextInt();
while (number2 != 0){
switch (number2){
case 1:
InsertSort(a);
PrintThem(a);
break;
case 2:
low = 0;
high = a.length;
QuickSort(a, low, high);
PrintThem(a);
break;
case 3:
SelectionSort(a);
PrintThem(a);
break;
case 4:
BubbleSort(a);
PrintThem(a);
break;
default:
System.out.println("Input error! Try later!");
break;
}
System.out.println("\n\n1.Insert Sort \t 2.Quick Sort \t" +
" 3.Select Sort \t 4.Bubble Sort \t 0.Abort");
System.out.print("Input your chose here: ");
number2 = reader.nextInt();
}
if (number2 == 0)
System.out.print("\tBye~Bye~");
}
}
更多信息請(qǐng)查看IT技術(shù)專欄