您的位置:首页 > 编程语言 > Java开发

Java中常用的数组排序算法

2017-06-05 19:23 253 查看
冒泡排序:

双层循环实现。外层循环控制排序轮数,内层循环对比数组中每个临近元素的大小,以确定是否交换位置

程序:从小到大

public class BubbleSort {
public static void main (String [] args) {
int [] array = {63 , 4 , 24 , 1 , 3 , 15};
BubbleSort sorter = new BubbleSort();   //Create a bubble sort class object
sorter.sort(array);
}

/*
* Bubble sort
*/
public void sort(int[] array) {
for (int i = 1 ; i < array.length ; i ++) {
//Compare adjacent two elements, large back bubble
for (int j = 0 ; j < array.length - i ; j ++) {
if (array[j] > array [j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
showArray(array);   //output the array element after bubble sort
}

/*
*  Display all the elements in the array
*/
public void showArray(int[] array) {
for (int i : array){
System.out.print(">" + i);
}
System.out.println();
}
}


直接选择排序:

将制定排序位置与其他数组元素分别对比,如果满足条件就交换元素

与冒泡排序相比,直接选择排序的交换次数要少很多,所以速度回快些

例子:从小到大

public class SelectSort {
public static void main(String[] args) {
int [] array = {63 , 4 , 24 , 1 , 3 , 15};
SelectSort sorter = new SelectSort();   //Create a Select sort class object
sorter.sort(array);
}

/*
* SelectSort
*/
public void sort (int[] array) {
int index;
for (int i = 1 ; i < array.length ; i ++) {
index = 0;
for (int j = 1 ; j <= array.length - i ; j ++){
if (array[j] > array[index]) {
index = j;
}
}
//交换位置 array.length - i 和 index上的两个数
int temp = array[array.length - i];
array[array.length - i] = array[index];
array[index] = temp;
}
showArray(array);
}

public void showArray(int[] array) {
for (int i : array) {
System.out.print(">" + i);
}
System.out.println();
}
}


反转排序:

以相反的顺序把原有数组的内容从新排序

例子:

public class ReverseSort {
public static void main(String[] args) {
int [] array = {10 , 20 , 30 , 40 , 50 , 60};
ReverseSort sorter = new ReverseSort(); //Create a Select sort class object
sorter.sort(array);
}

/*
* ReverseSort
*/
public void sort (int[] array) {
System.out.println("数组原有内容:");
showArray(array);
int temp;
int len = array.length;
for (int i = 0 ; i < len / 2 ; i ++) {
temp = array[i];
array[i] = array[len - 1 - i];
array[len - 1 - i] = temp;
}
System.out.println("数组反转后内容:");
showArray(array);
}
public void showArray(int[] array) {
for (int i : array) {
System.out.print("\t" + i);
}
System.out.println();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: