Bubble sort: bubbling
Insertion sort: incremental approach (增量靠近)
Merge sort: divide-and conquer(分而治之)
Quick sort: location (元素定位
快速排序
int partition(sqlist &l, int low, int high)
{
l.r[0] = l.r[low];
pivorkey = l.r[low].key;
while(low < high){
while(low <high&&l.r[high].key >= pivotkey) --high;
l.r[low] = l.r[high];
while(low <high&&l.r[low].key<= pivotkey) ++low;
l.r[high] = l.r[low];
}
l.r[low] = l.r[0];
return low;
}
void qsort(sqlist &l, int low, int high){
if(low < high)
pivotloc = partition(l, low, high);
qsort(l, low , pivotloc-1);
qsort(l, pivotloc+1,high);
}
1.自底向上算法
#include <stdio.h> #include <time.h> void Merge(int *a,int low,int mid,int high) { int i = low,j = mid + 1,k = 0; int *temp = (int *)malloc((high - low + 1)*sizeof(int)); while(i <= mid && j <= high) a[i] < a[j] ? (temp[k++] = a[i++]):(temp[k++] = a[j++]); while(i <= mid) temp[k++] = a[i++]; while(j <= high) temp[k++] = a[j++]; memcpy(a + low,temp,(high -low + 1)*sizeof(int)); free(temp); } void MergeSort(int *a,int n) { int length; for(length = 1;length < n;length *= 2) { int i; for( i = 0;i + 2*length - 1 <= n - 1;i += 2*length) Merge(a,i,i+length-1,i+2*length -1); if(i + 2*length - 1 <= n - 1)//尚有两个子文件,其中后一个长度小于length Merge(a,i,i +2* length -1,n - 1); } } int main() { int n; cin >> n; int *data = new int[n]; if(!data) exit(1); int k = n; while(k --) { cin >> data[n-k-1]; } clock_t s = clock(); MergeSort(data, n); clock_t e = clock(); k = n; while(k --){ cout << data[n-k-1] << ' '; } cout << endl; cout << "the algrothem used " << e-s << " miliseconds."<< endl; delete data; return 0;}
void mergeSort(struct RECORD arr_buffer[][40])
{
int length;
for (length = 1; length < _FILE_NUM_ ; length *= 2 )
{
MergePass(arr_buffer, length);
}
}
void MergePass(SeqList R,int length)
{
int i;
for(i=1;i+2*length-1<=n;i=i+2*length)
Merge(R,i,i+length-1,i+2*length-1);
if(i+length-1<n)
Merge(R,i,i+length-1,n);
}
void Merge(int *a,int low,int mid,int high)
{
int i = low,j = mid + 1,k = 0;
int *temp = (int *)malloc((high - low + 1)*sizeof(int));
while(i <= mid && j <= high)
a[i] < a[j] ? (temp[k++] = a[i++]):(temp[k++] = a[j++]);
while(i <= mid)
temp[k++] = a[i++];
while(j <= high)
temp[k++] = a[j++];
memcpy(a + low,temp,(high -low + 1)*sizeof(int));
free(temp);
}