基本排序总结
排序
冒泡排序
基本思想从输入序列的第一个元素到最后一个元素进行两两比较。以最小序列为例,最小元素会如同气泡一样漂浮到序列顶端。
//O(n^2)
void bubbleSort(int[] a){
for(int i = 0;i < a.length -1;i++){
for(int j = 0; j < a.length-1-i;j++){
if(a[j] > a[j+1]){
int temp = a[i];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
//O(n^2)
void bubbleSortedImproved(int[] a){
boolean swap = true;
for(int i = 0;i < a.length - 1 && swap;i++){
swap = false;
for(j = 0;j < a.length-1-i;j++){
if(a[j] > a[j+1]){
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
swap = true;
}
}
}
选择排序
寻找最小值,用当前位置和最小值交换。直到序列排好序
//O(n^2)
void selectSort(int[] a){
int minIdx;
for(int i = 0;i < a.length-1;i++){
minIdx = i;
for(j = i+1;j < a.length;j++){
if(a[j] < a[min]){
min = j
}
}
//swap
temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
插入排序
从输入序列中移除一个元素到待插入序列的正确位置,直到每个元素都被选择一次
//O(n^2)
void intsertSort(int[] a){
int j,temp;
//默认从第二项开始
for(int i = 1;i <= a.length - 1;i++){
temp = a[i];
j = i;
while(a[j-1] > temp && j >= 1){
a[j] = a[j-1];
j--;
}
a[j] = temp;
}
希尔排序
N间距的插入排序,使用不同的间距比较元素,通过逐渐减少间距最终完成一次常规插入排序
//时间复杂度取决于间距
void shellSort(int[] a){
int gap = a.length;
int temp,k;
while(true){
gap = gap / 2;
for(int i = 0; i < gap;i++){
for(int j = gap + 1;j < a.length;j++){
temp = a[j];
k = j;
while(k > gap && a[k-gap] > temp){
a[k] = a[k-gap];
k = k-gap;
}
a[k] = temp
}
}
if(gap == 1){
break;
}
}
}
归并排序
分治和归并的思想进行的排序,小文件开始大文件结束
//O(nlogn)
void mergeSort(int[] a,int left,int right){
int mid;
if(right > left){
mid = (right -1 + left) / 2;
mergeSort(a,left,mid);
mergeSort(a,mid+1,right);
merge(a,left,mid,right);
}
}
void merge(int[] a,int left,int mid,int right){
int temp = new int[right-left+1];
int i = 0;
int l = left;
int m = mid+1;
while(l <= mid && m <= right){
temp[i++] = a[l] < a[m] ? a[l++] : a[m++];
}
while(l <= mid){
temp[i++] = a[l++];
}
while(m <= right){
temp[i++] = a[m++];
}
for(int i = left;i <= right;i++){
a[i] = temp[i];
}
}
快速排序
大文件开始小文件结束
//O(nlogn)
quickSort(int[] a,int low,int high){
int pivot;
if(high > low){
privot = partition(a,low,high);
quickSort(a,low pivot - 1);
quickSort(a,pivot+1,high);
}
}
int partition(int[] a,int low,int high){
int left = low;
int right = high;
int pivot = a[low];
while(left < right){
while(a[left] <= pivot){
left++;
}
while(a[rihjt] > pivot){
right--;
}
if(left < right){
swap(a,left,right);
}
}
a[low] = a[right];
a[right] = pivot;
return right;
}
void swap(int[] a,int left,int right){
int temp = a[left];
a[left] = a[ritght];
a[right] = temp;
}

浙公网安备 33010602011771号