java多种排序方法代码集合
2015-04-16来源:易贤网

最近在学习java,想练习一下编写,使用了eclipse编写了如下的排序代码。其中包含了快速排序, 选择排序,插入排序,冒泡排序。

/*

*

* Roc

*

* 2013/10/4

*

* 此段代码主要是通过java来实现多种排序

*

*/

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];//用于保存划分方法返回的结果

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;

}

//用于整数之间进行的交换

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~");

}

}

更多信息请查看IT技术专栏

2025公考·省考培训课程试听预约报名

  • 报班类型
  • 姓名
  • 手机号
  • 验证码
推荐信息