排序:
插入排序:直接插入排序、希尔排序
交换排序:冒泡排序、快速排序
选择排序:简单选择排序、堆排序
归并排序
基数排序
/***
** 插入排序
** 时间复杂度:O(n2) 空间复杂度:O(1)
** 稳定性:稳定
** 后移数据,往前面插
* 外层循环记录下标为1及后面的数据到temp中,内层循环将temp的数据往前面移放到合适的位置
*/
public class SortInsert {
public static void main(String[] args) {
int[] arr= {11,15,8,1,5,99,88};
System.out.println("排序前:"+Arrays.toString(arr));
for(int i=1;i<arr.length;i++){//从下标为1的数据开始比较
int temp = arr[i];
int j = i-1;
while(j>=0 && arr[j]>temp){ //j是i的前面一个数据的下标
arr[j+1] = arr[j]; //前面那个数据大于它的话,就后推
j--;
}
arr[j+1] = temp; //最后找到它的位置,插入
}
System.out.println("排序后:"+Arrays.toString(arr));
}
}
/***
** 冒泡
** 时间复杂度:O(n2) 空间复杂度:O(1)
** 稳定性:稳定排序
** 两两相邻比较,交换
*/
public class SortBubble {
public static void main(String[] args) {
int[] arr= {11,15,8,1,5,99,88};
System.out.println("排序前:"+Arrays.toString(arr));
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr.length-i-1;j++) {
if(arr[j]>arr[j+1]) {
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
System.out.println("排序后:"+Arrays.toString(arr));
}
}
/***
** 快排
** 时间复杂度:O(nlog2 n) 空间复杂度:O(nlog2 n)
** 稳定性:不稳定
** 两头往中间找合适的位置,递归
*/
public class SortQuick {
public static void main(String[] args) {
int[] arr= {11,15,8,1,5,99,88};
System.out.println("排序前:"+Arrays.toString(arr));
sort(arr,0,arr.length-1);
System.out.println("排序后:"+Arrays.toString(arr));
}
public static void sort(int[] arr , int low , int high) {
//左边的下表不能大于右边的下表
if(low > high) {
return;
}
int left=low;
int right=high;
int temp=arr[low];//基准数据
while(low < high) {
//假如右边游标小于基准数据,交换
while(low < high && arr[high] >= temp) {
high--;
}
arr[low] = arr[high];
//假如左边游标大于基准数据,交换
while(low < high && arr[low] <= temp) {
low++;
}
arr[high]=arr[low];
}
arr[low]=temp;
sort(arr,left,low-1);
sort(arr,low+1,right);
}
}
/***
** 简单选择排序
** 时间复杂度:O(n2) 空间复杂度:O(1)
** 稳定性:不稳定
** 选小的往前面移,和冒泡有点像
*/
public class SortSimple {
public static void main(String[] args) {
int[] arr= {11,15,8,1,5,99,88};
System.out.println("排序前:"+Arrays.toString(arr));
for (int i = 0; i < arr.length; i++) {
int position =i; //先定义下标和值
int temp = arr[i];
for (int j = i+1; j < arr.length; j++) {
if (arr[j] < temp) { //求最小的下标和值
position = j;
temp=arr[position];
}
}
arr[position]=arr[i]; //交换
arr[i]=temp;
}
System.out.println("排序后:"+Arrays.toString(arr));
}
}
查找:
直接查找、二分法查找(折半查找)
######## 直接查找比较简单就不写代码了
public class BInarySearch {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr= {1,5,8,11,15,99,88};
System.out.println("位置是:"+(sort(arr,5)+1));
}
private static int sort(int[] arr,int num) {
int lower=0;
int high=arr.length-1;
while(lower<high) {
int middle=(lower+high)/2;
if(arr[middle]<num) {
lower=middle+1;
}else if(num<arr[middle]){
high=middle-1;
}else {
return middle;
}
}
return num;
}
}
先好好消耗一下这几种排序和查找,还有部分基本排序慢慢来。