数组
1. 排序算法——快速排序
#include <stdio.h>
void quickSort(int src[], int start, int end){
if(start >= end){
return;
}
int i = start;
int j = end;
int value = src[i];
int tmp = i;
while(i < j){
while(i < j && src[j] >= value){
j--;
}
src[tmp] = src[j];
tmp = j;
while(i < j && src[i] <= value){
i++;
}
src[tmp] = src[i];
tmp = i;
}
src[i] = value;
quickSort(src, start, i-1);
quickSort(src, i+1, end);
return;
}
int main(){
int src[] = {34,45,21,18,4,9,25,90};
quickSort(src, 0, 7);
for(int i=0; i<8; i++){
printf("%d\n", src[i]);
}
}
2. 排序算法——冒泡排序
#include <stdio.h>
int * bubble(int src[], int n){
if(n <=1){
return src;
}
int i,j,tmp;
for(i=0; i<n; i++){
for(j=i+1; j<n; j++){
if(src[j] < src[i]){
tmp = src[j];
src[j] = src[i];
src[i] = tmp;
}
}
}
return src;
}
int main(){
int src[8] = {3,11,8,10,7,23,5,7};
bubble(src, 8);
for(int i=0;i<8;i++){
printf("%d\n", src[i] );
}
}
3. 排序算法——插入排序
4. 折半查找/二分查找
#include <stdio.h>
#include <string.h>
int search(int src[], int len, int value){
int start = 0;
int end = len - 1;
int mid;
while(start <= end){
mid = (start + end) >> 1 ;
if(value == src[mid]){
return mid;
}else if(value > src[mid]){
start = mid + 1;
}else{
end = mid - 1;
}
}
return -1;
}
int main(){
int src[] = {1,2,3,4,5,6,7};
int res = search(src, 7, 7);
printf("%d\n", res);
}
5. 求前K大的数
6. 寻找数组中的最大值和最小值
7. AB两个有序数组,元素去重合并
//mergeArray.cpp
#include <stdio.h>
int * mergeArray(int a[], int b[], int c[], int lenA, int lenB, int &lenC) {
int i = 0;
int j = 0;
int m = 0;
lenC = 0;
while(i < lenA && j < lenB){
if(a[i] < b[j]){
c[m] = a[i];
i++;
m++;
lenC++;
}else if(a[i] > b[j]){
c[m] = b[j];
j++;
m++;
lenC++;
}else{
c[m] = a[i];
i++;
j++;
m++;
lenC++;
}
}
if(i == lenA && j < lenB){
while(j < lenB){
c[m] = b[j];
j++;
m++;
lenC++;
}
}else if(j == lenB && i < lenA){
while(i < lenA){
c[m] = a[i];
i++;
m++;
lenC++;
}
}
return c;
}
int main(){
int a[5] = {2,3,7,8,11};
int b[6] = {3,9,10,12,88,89};
int c[11];
int len = 0;
mergeArray(a, b, c, 5, 6, len);
for(int i=0; i<len; i++){
printf("%d\n", c[i]);
}
}
8. 求数组的子数组之和的最大值
9. 求数组中最长递增子序列
10. 数组循环右移
把一个含有N个元素的数组,循环右移K位,要求时间复杂度为O(N),且只允许使用两个附加变量。
11. 数组分割
有一个无序,元素个数为2n的正整数数组,要求:如何能把这个数组分割成元素个数为n的两个数组,并使两个子数组的和最接近。