一、冒泡排序原理及实战
* 代码实战:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct{
ElemType *elem;
int TableLen;
}SSTable;
void InitTable(SSTable &ST,ElemType count)
{
ST.TableLen=count;
int i;
srand(time(NULL));
ST.elem=(ElemType*)malloc(sizeof(ElemType)*ST.TableLen);
for(i=0;i<ST.TableLen;i++)
{
ST.elem[i]=rand() % 100;
}
}
void PrintTable(SSTable ST)
{
int i;
for(i=0;i<ST.TableLen;i++)
{
printf("%3d",ST.elem[i]);
}
printf("\n");
}
void reverse(ElemType &a,ElemType &b)
{
ElemType temp;
temp=a;
a=b;
b=temp;
}
void BubbleSearch(ElemType *data,ElemType count)
{
bool flag;
int i,j;
for(j=0;j<count-1;j++)
{
flag= false;
for(i=count-1;i>j;i--)
{
if(data[i-1]>data[i])
{
reverse(data[i-1],data[i]);
flag= true;
}
}
if(false==flag)
{
return;
}
}
}
int main() {
SSTable ST;
InitTable(ST,10);
PrintTable(ST);
BubbleSearch(ST.elem,10);
PrintTable(ST);
return 0;
}
二、快速排序原理及实战
* 快速排序实战:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
typedef int ElemType;
typedef struct{
ElemType *elem;
int TableLen;
}SSTable;
void InitTable(SSTable &ST,ElemType count)
{
ST.TableLen=count;
ST.elem=(ElemType*)malloc(sizeof(ElemType)*ST.TableLen);
int i;
srand(time(NULL));
for(i=0;i<ST.TableLen;i++)
{
ST.elem[i]=rand() % 100;
}
}
void PrintTable(SSTable ST)
{
int i;
for(i=0;i<ST.TableLen;i++)
{
printf("%3d",ST.elem[i]);
}
printf("\n");
}
int Division(ElemType *A,ElemType low,ElemType high)
{
ElemType temp=A[low];
while(low<high)
{
while(low<high&&A[high]>=temp)
{
high--;
}
A[low]=A[high];
while(low<high&&A[low]<=temp)
{
low++;
}
A[high]=A[low];
}
A[high]=temp;
return high;
}
void QuickSearch(ElemType *A,ElemType low,ElemType high)
{
if(low<high)
{
ElemType pos_return=Division(A,low,high);
QuickSearch(A,low,pos_return-1);
QuickSearch(A,pos_return+1,high);
}
}
int main() {
SSTable ST;
InitTable(ST,10);
// ElemType A[10]={ 64, 94, 95, 79, 69, 84, 18, 22, 12 ,78};
// memcpy(ST.elem,A,sizeof(A));
PrintTable(ST);
ElemType low=0,high=ST.TableLen-1;
QuickSearch(ST.elem,low,high);
PrintTable(ST);
return 0;
}
三、插入排序原理及实战
* 代码实战:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int ElemType;
typedef struct{
ElemType *elem;
int TableLen;
}SSTable;
void InitTable(SSTable &ST,ElemType count)
{
ST.TableLen=count;
ST.elem=(ElemType*)malloc(sizeof(ElemType)*ST.TableLen);
int i;
srand(time(NULL));
for(i=0;i<ST.TableLen;i++)
{
ST.elem[i]=rand() % 100;
}
}
void PrintTable(SSTable ST)
{
int i;
for(i=0;i<ST.TableLen;i++)
{
printf("%3d",ST.elem[i]);
}
printf("\n");
}
void InsertSort(ElemType *A,ElemType count)
{
ElemType i,j,temp;
for(i=1;i<count;i++)
{
temp=A[i];
for(j=i-1;j>=0&&A[j]>temp;j--)
{
A[j+1]=A[j];
}
A[j+1]=temp;
}
}
int main() {
SSTable ST;
InitTable(ST,10);
PrintTable(ST);
InsertSort(ST.elem,10);
PrintTable(ST);
return 0;
}