// datastructure.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdio.h"
#include "string.h"
#include <windows.h>
#include "MyTest.h"
typedef struct Student
{
char * name;
int age;
} TStudent;
void bubbleSort(int *a,int len);
void selectSort(int *a,int len);
void insertSort(int * a,int len);
void quickSort(int * a,int left,int right);
void printArray(int *a,int len);
void swap(int *a,int *b);
void insertArray(int *a,int len ,int i,int j);
int main(int argc, char* argv[])
{
int a[7] = {49,38,65,97,76,13,27};
printf("排序前:");
printArray(a,7);
//selectSort(a,10);
//insertSort(a,10);
quickSort(a,0,6);
printf("排序后");
printArray(a,7);
return 0;
}
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void printArray(int *a,int len){
printf("\r\n-------------------------\r\n");
for (int k1=0;k1<len;k1++)
{
printf("%d ",a[k1]);
}
printf("\r\n-------------------------\r\n");
}
//冒泡排序
void bubbleSort(int *a,int len){
int minindex = 0;
for(int i=0;i<len;i++){
for (int j=len-1;j>i;j--){
if( a[j-1] > a[j] ){
swap(&a[i],&a[minindex]);
}
}
printf("\r\n\r\n第%d次排序结果:\n",i);
for (int k=0;k<len;k++)
{
printf("%d ",a[k]);
}
}
printf("\r\n\r\n");
}
//选择排序
void selectSort(int *a,int len){
int minindex = 0;
for(int i=0;i<len;i++){
minindex = i;
for(int j=i+1;j<len;j++){
if(a[j]<a[minindex]){
minindex = j;
}
}
if( i != minindex ){
swap(&a[i],&a[minindex]);
}
}
}
void insertArray(int *a,int len ,int i,int j){
int temp = a[j];
for(int k=j;k>i;k--){
a[k] = a[k-1];
}
a[i] = temp;
}
//插入排序
void insertSort(int * a,int len){
for(int i=0;i<len;i++){
for(int j=0;j<i;j++){
if( a[j] > a[i] ){
insertArray(a,len,j,i);
break;
}
}
}
}
//快速排序
void quickSort(int * a,int left,int right){
int temp = a[(left+right)/2];
int lefttemp = left;
int righttemp = right;
while( lefttemp < righttemp ){
while( a[righttemp] > temp ){
righttemp--;
}
while( a[lefttemp] < temp ){
lefttemp++;
}
if(lefttemp<=righttemp){
swap(&a[righttemp],&a[lefttemp]);
lefttemp++;
righttemp--;
}
}
if(lefttemp == righttemp){
lefttemp++;
}
if(left<righttemp){
quickSort(a,left,lefttemp-1);
}
if(lefttemp<right){
quickSort(a+1,righttemp+1,right);
}
}