一、冒泡:
时间复杂度:O( n^2 )
空间复杂度:O(1)
原理:相邻元素两两比较,顺序相反则两个互换,直到遍历到最后完全有序
import java.util.Arrays;
public static void bubbleSort(int[] array) {
int size = array.length;
// loop to access each array element
for (int i = 0; i < size - 1; i++)
// loop to compare array elements
for (int j = 0; j < size - i - 1; j++)
// compare two adjacent elements
// change > to < to sort in descending order
if (array[j] > array[j + 1]) {
// swapping occurs if elements
// are not in the intended order
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
二、快排
时间复杂度:O( n )
空间复杂度:O(logn)
原理:
分别从初始序列“6 1 2 7 9 3 4 5 10 8”两端开始“探测”。先从右往左找一个小于6的数,再从左往右找一个大于6的数,然后交换他们。哨兵i和哨兵j相遇了,哨兵i和哨兵j都走到3面前。说明此时“探测”结束。我们将基准数6和3进行交换。
现在基准数6已经归位,它正好处在序列的第6位。此时我们已经将原来的序列,以6为分界点拆分成了两个序列,左边的序列是“3 1 2 5 4”,右边的序列是“9 7 10 8”。接下来还需要分别处理这两个序列。因为6左边和右边的序列目前都还是很混乱的。不过不要紧,我们已经掌握了方法,接下来只要模拟刚才的方法分别处理6左边和右边的序列即可。
public static void quickSort(int[] nums, int start, int end){
if(start>end) return;
int i,j,base;
i=start;
j=end;
base=nums[start];
while (i<j){
while (i<j && nums[j]>=base) j--;
while (i<j && nums[i]<=base) i++;
if(i<j){
swap(nums,i,j);
}
}
swap(nums,start,i);
quickSort(nums,start,j-1);//左边的序列
quickSort(nums,j+1,end);//右边的序列
}
public static void swap(int[] nums,int left,int right){
int temp=nums[left];
nums[left]=nums[right];
nums[right]=temp;
}
三、插入排序
时间复杂度:O( n^2 )
空间复杂度:O(1)
原理:
1.从第一个元素开始,该元素可以认为已经被排序
2.取下一个元素tem,从已排序的元素序列从后往前扫描
3.如果该元素大于tem,则将该元素移到下一位
4.重复步骤3,直到找到已排序元素中小于等于tem的元素
5.tem插入到该元素的后面,如果已排序所有元素都大于tem,则将tem插入到下标为0的位置
6.重复步骤2~5
public static void insertSort(int[] array){
for (int i = 1; i <array.length ; i++) {
int tmp = array[i];
int j = i-1;
for ( ;j >=0; j--) {
if (array[j]>tmp){
array[j+1]=array[j];
}else
{
// array[j+1]=tmp;
break;
}
}
array[j]=tmp;
}
}
四、选择排序
时间复杂度:O( n^2 )
空间复杂度:O(1)
原理:
首先遍历n个元素,找到最小值,将它与第一个元素互换,在遍历剩下的n-1,…2,
public static void selectionSort(int[] nums) {
int length=nums.length;
//最小值的索引
int index;
for(int i=0;i<length;i++){
index=i;
for(int j=i+1;j<length;j++){
//寻找最小的值
if(nums[j]<nums[index]){
index=j;
}
}
int tem=nums[i];
nums[i]=nums[index];
nums[index]=tem;
}
}