二分查找:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//法一,非递归实现
int second_find(int *L,int key,int low,int sizearray)
{
int mid = 0;
int high = sizearray - 1;
while(low <= high)
{
mid = (low + high)/2
if (key < L[mid])
{
high = mid - 1;
}
else if (key > L[mid])
{
low = mid + 1;
}
else
{
return mid;
}
}
}
//法二,递归实现
int send_find2(int *L,int key,int low,int high)
{
if (low <= high)
{
int mid = (low+high)/2;
if (key < L[mid])
{
send_find2(L,key,low,mid -1);
}
else if(key > L[mid])
{
send_find2(L,key,mid + 1,high);
}
else
{
return mid;
}
}
else
{
return -1;
}
}
int main(int argc,char *argv)
{
int a[5] = {1,2,3,4,5};
int num = second_find(a,2,0,sizeof(a)/sizeof(a[0]));
}
快速排序:
int paintion(int *L,int low,int high)
{
int poit = L[low];
while(low < high)
{
while(low < high && L[low] <= poit)
low++;
swap(L,low,high);
while(low < high && L[high] >= poit)
high--;
swap(L,low,high);
}
return low;
}
void Qsort(int *L,int low,int high)
{
int poit = 0;
if (low < high)
{
poit = paintion(L,low,high);
Qsort(L,poit+1,high);
Qsort(L,low,poit - 1);
}
}
int main(int argc,char *argv[])
{
return 0;
}
快速排序优化
#include <stdio.h>
int paintion(int *L,int low,int high)
{
int poit = L[low];
while(low < high)
{
while(low < high && L[high] >= poit)
high--;
L[low] = L[high];
while(low < high && L[low] <= poit)
low++;
L[high] = L[low];
}
L[low] = poit;
return low;
}
void Qsort(int *L,int low,int high)
{
if (low < high)
{
int poit = paintion(L,low,high);
Qsort(L,low,poit - 1);
Qsort(L,poit + 1,high);
}
}
int main(int argc,char *argv[])
{
int a[20] = {10,9,16,3,17,7,19,20,11,1,15,12,4,5,14,2,6,18,8,13};
Qsort(a,0,19);
int i = 0;
for (;i<20;i++)
{
printf("a:%d\n",a[i]);
}
return 0;
}