一:排序
1.冒泡排序:其基本原理是相邻的两个数进行比较
public class BubbleSort {
public void bubbleSort(int[] arr) {
int temp;
int sum = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = arr.length - 1; j >i; --j) {
if (arr[j - 1] > arr[j]) {//冒泡的核心:相邻的进行比较,而不是外层元素依次和内层元素比较,倒叙和升序也在这里控制
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
sum++;//查看外层循环进行的次数
}
System.out.println(sum);
for (int m = 0; m < arr.length; m++) {
System.out.println(arr[m]);
}
}
public static void main(String[] args) {
int[] arr =new int[] { 3, 55, 66, 43, 63, 24,32, 44, 23, 534, 532, 64 };
newBubbleSort().bubbleSort(arr);
}
}
时间复杂度为O(N^2) (比较次数N*N/2,交换N*N/4)这个怎么算的?;
适用于n比较小的情况
2.选择排序
基本原理是选取要比较的数依次与后面的数进行比较,先把要比较数做一个标记A,把满足条件的那一位进行标记B,循环比较一次结束以后将标记为A的数的位置与标记为B的位置的数进行替换。如果没有就和本身进行替换
public classSelectionSort {
public void selectSort(int [] intArr){
int max,in,out,temp;
for(out=0;out<intArr.length;out++){//控制循环的次数
max = out;//把要进行比较的数进行标记A
for(in=out+1;in<intArr.length;in++){
if(intArr[max]<intArr[in]){//如果小于则将标记交换
max = in;//内层循环结束后,这里是标记B
}
}
temp = intArr[out];//下面三步是将两个标记的数进行交换
intArr[out]= intArr[max];
intArr[max] = temp;
}
for(int x :intArr){
System.out.print(x+":");
}
}
public static void main(String[] args) {
//int intArr[] =new int[]{13,2,34,132,432,34,53,13,56,34,224,1344,554,22344,23453,3,555,666,223};
int intArr[] =new int[]{4,3,2,1};
newSelectionSort().selectSort(intArr);
}
}
时间复杂度:O(N*N),比较N*N/2,交换<N;与冒泡相比,比较次数没有明显改变,但交换次数明显减少许多。
适用于n比较小的情况
3.插入排序(适用于部分数据已经排好序的情况)
核心思想是:依次取出要排序的那个数字分别与排好序的数据进行依次比较,找到那个满足条件的数的前一个停止比较,进行插入,。
时间复杂度:O(n^2) ,比较N*N/4,复制N*N/4;插入排序在随机数的情况下比冒泡快一倍,比选择稍快;在基本有序的数字中,插入几乎只需O(N);在逆序的情
//况下,不必冒泡快。
package com.yxyt.sort;
public class InsertSort {
/**
* 插入排序
*/
public void insertSort(int[] arr) {
int j, temp;
for (int i = 0; i < arr.length; i++) {
j = i - 1;//因为每次都是和他本身前一个比较。
temp = arr[i];
for (; j >=0; j--) {
if (temp < arr[j]) {
arr[j + 1] = arr[j];不符合条件依次向后移
} else {
break;//找到满足条件退出比较
}
}
arr[j + 1] = temp;
}
for (int x : arr) {
System.out.print(x +"!");
}
}
public static void main(String[] args) {
int intArr[] =new int[] { 13, 2, 34, 132, 432,34, 53, 13, 56, 34,
224, 1344, 554, 22344,23453, 3, 555, 666, 223 };
// int intArr[] =new int[]{4,3,2,1};
newInsertSort().insertSort(intArr);
}
}