一沙一世界, 一花一天堂。

数组排序方法

[Java] 韩玉龙 2016-05-16 15:09:25 点击率:2471次

/**
* 冒泡排序算法,时间复杂度O(n2),算法具有稳定性,堆排序和快速排序算法不具有稳定性,即排序后相同元素的顺序会发生变化
*
* @param src
*/
public static void bubbleSort(int[] src) 
{
	if (src.length > 0) 
	{
		int length = src.length;
 		for (int i = 1; i < length; i++) { for (int j = 0; j < length - i; j++) { if (src[j] > src[j + 1])
	 			{
				int temp = src[j];
				src[j] = src[j + 1];
				src[j + 1] = temp;
				}
			}
		}
	}
}
/**
* 快速排序,时间复杂度O(nlogn),最坏时间复杂度O(n2),平均时间复杂度O(nlogn),算法不具稳定性 package dataConstrucation2;
public class QuickSort {
/**
* 快速排序
* @param strDate
* @param left
* @param right
*/
public void quickSort(String[] strDate, int left, int right) 
{
	String middle, tempDate;
	int i, j;
 	i = left;// 最左边下标
	j = right;// 最右边下标
	middle = strDate[(i + j) / 2];// 中间元素 
	do {
		while (strDate[i].compareTo(middle) < 0 && i < right) i++; // 找出左边比中间值大的数 while (strDate[j].compareTo(middle) > 0 && j > left)
		j--; // 找出右边比中间值小的数
		if (i <= j) { // 将左边大的数和右边小的数进行替换 tempDate = strDate[i]; strDate[i] = strDate[j]; strDate[j] = tempDate; i++; j--; } } while (i <= j); // 当两者交错时停止 if (i < right) { quickSort(strDate, i, right); } if (j > left) {
		quickSort(strDate, left, j);
	}
}
/**
* 选择排序,分为简单选择排序、树形选择排序(锦标赛排序)、堆排序 此算法为简单选择排序
*
* @param a
*/
public static void selectSort(int[] a) 
{
	int length = a.length;
	for (int i = 0; i < length; i++) { int minIndex = i; for (int j = i + 1; j < a.length; j++) { if (a[j] < a[minIndex]) { minIndex = j; } } if (minIndex != i) { int temp = a[minIndex]; a[minIndex] = a[i]; a[i] = temp; } } } /** * 插入排序,适用于少量数据的排序,时间复杂度O(n2),是稳定的排序算法,原地排序 * * @param a */ public static void insertSort(int[] a) { int length = a.length; for (int i = 1; i < length; i++) { int temp = a[i]; int j = i; for (; j > 0 && a[j - 1] > temp; j--)
		 {
		 a[j] = a[j - 1];
		}
		a[j] = temp;
	}
}