几种排序、查找算法
快速排序
void quickSort(int a[],int l,int r){
if(l>=r){
return ;
}
int mid=partition(a,l,r);
quickSort(a,l,mid-1);
quickSort(a,mid+1,r);
}
int partition(int a[],int low,int high){
int pivot = a[low];
while(low<high){
while(low<high&&a[high]>=pivot){
high--;
}
if(low<high){
a[low]=a[high];
}
while(low<high&&a[low]<=pivot){
low++;
}
if(low<high){
a[high]=a[low];
}
}
a[low]=pivot;
return low;
}
插入排序
void insertionSort(int a[],int n){
for(int i=1;i<n;i++){
int temp=a[i];//temp是准备插入的值
for(int j=i-1;j>=0;j--){
if(a[j]>temp]){//如果值大于目标值就交换
a[j+1]=a[j];
a[j]=temp;
}else{
break;
}
}
}
}
选择排序
void selectSort(int a[],int n){
for(int i=0;i<n;i++){
int min=i;
for(int j=i+1;j<n;j++){//每次在未排序的数中找到最小的数的下标
if(a[min]>a[j]){
min=j;
}
}
if(min!=i){//将最小的数与a[i]交换
int t=a[i];
a[i]=a[min];
a[min]=t;
}
}
}
void selectSort(int a[],int n){
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
if(a[j]>a[i]){
int t=a[j];
a[j] = a[i];
a[i] = t;
}
}
}
}
冒泡排序
void bubbleSort(int a[],int n){
for(int i=0;i<n-1;i++){
for(int j=0;j<n;j++){
if(a[j]>a[j+1]){
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
二分查找
int binarySearch(int a[],int n,int target){
int left=0,right=n-1;
int mid = 0;
while(left<=right){
mid = (left+right)/2;//mid设置
if(a[mid]<target){
left=mid+1;
}else if(a[mid]>target){
right=mid-1;
}else{
return mid;
}
}
return -1;
}