十大经典排序算法
- 1.冒泡排序
原理:比较相邻的元素,第一个>第二个,就交换;对每一对都这么操作。
public static void bubbleSort(int[] nums){
int temp=0;
for(int i=0;i<nums.length;i++){
for(int j=0;j<nums.length-1;j++){
if(nums[j]>nums[j+1]){
temp=nums[j];
nums[j]=nums[j+1];
nums[j+1]=temp;
}
}
}
}
时间复杂度:O(n2)
空间复杂度:O(1)
- 2.选择排序
原理:每一次,都选择最小的数min和前面的交换;
public static void selectSort(int[] nums){
int temp=0;
for(int i=0;i<nums.length;i++){
int k=i;
for(int j=i+1;j<nums.length;j++){
if(nums[j]<nums[k]){
k=j;//最小值的索引
}
}
temp=nums[i];
nums[i]=nums[k];
nums[k]=temp;
}
}
- 3.插入排序
原理:假设前面的排序好了,后面的插入进去(打关牌)
public static void insertSort(int[] numbers) {
int size = numbers.length;
int temp = 0;
int j = 0;
for (int i = 0; i < size; i++) {
temp = numbers[i];
// 假如temp比前面的值小,则将前面的值后移
for (j = i; j > 0 && temp < numbers[j - 1]; j--) {
numbers[j] = numbers[j - 1];
}
numbers[j] = temp;
}
}
- 4.希尔排序
- 5.归并排序
原理:递归思想,二分法,左右两部分排序好后再排序;
public static int[] mergeSort(int[] nums, int low, int high) {
int mid = (low + high) / 2;
if (low < high) {
mergeSort(nums, low, mid); // 左边
mergeSort(nums, mid + 1, high); // 右边
merge(nums, low, mid, high); // 左右归并
}
return nums;
}
public static void merge(int[] nums, int low, int mid, int high) {
int[] temp = new int[high - low + 1];
int i = low;// 左指针
int j = mid + 1;// 右指针
int k = 0;
// 把较小的数先移到新数组中
while (i <= mid && j <= high) {
if (nums[i] < nums[j]) {
temp[k++] = nums[i++];
} else {
temp[k++] = nums[j++];
}
}
// 把左边剩余的数移入数组
while (i <= mid) {
temp[k++] = nums[i++];
}
// 把右边边剩余的数移入数组
while (j <= high) {
temp[k++] = nums[j++];
}
// 把新数组中的数覆盖nums数组
for (int k2 = 0; k2 < temp.length; k2++) {
nums[k2 + low] = temp[k2];
}
}
- 6.快速排序
原理:递归思想,从前往后,找一个基准,遍历后面的元素,把小于它的都放在它的身后;
public static int getMiddle(int[] numbers, int low, int high) {
// 数组的第一个作为中轴
int temp = numbers[low];
while (low < high) {
while (low < high && numbers[high] > temp) {
high--;
}
// 比中轴小的记录移到低端
numbers[low] = numbers[high];
while (low < high && numbers[low] < temp) {
low++;
}
// 比中轴大的记录移到高端
numbers[high] = numbers[low];
}
numbers[low] = temp; // 中轴记录到尾
return low; // 返回中轴的位置
}
public static void quick(int[] numbers, int low, int high) {
if (low < high) {
int middle = getMiddle(numbers, low, high); // 将numbers数组进行一分为二
quick(numbers, low, middle - 1); // 对低字段表进行递归排序
quick(numbers, middle + 1, high); // 对高字段表进行递归排序
}
}
public static void quickSort(int[] numbers) {
// 查看数组是否为空
if (numbers.length > 0)
{
quick(numbers, 0, numbers.length - 1);
}
}