本文主要是介绍数据结构之排序(冒泡,选择,插入,快排),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
冒泡排序:---------------------------------------------------------
#include <stdio.h>
#define SIZE 8
void bubble_sort(int a[], int n);
void bubble_sort(int a[], int n)
{
int i, j, temp;
for (j = 0; j < n - 1; j++)
for (i = 0; i < n - 1 - j; i++)
{
if(a[i] > a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}
int main()
{
int number[SIZE] = {95, 45, 15, 78, 84, 51, 24, 12};
int i;
bubble_sort(number, SIZE);
for (i = 0; i < SIZE; i++)
{
printf("%d\n", number[i]);
}
printf("\n");
}
选择排序:-----------------------------------------------------
#include<stdio.h>
#define SIZE 8
void selectSort(int * array);
int main()
{
int array[8]={3,6,9,-3,9,2,1,45};
int i;
selectSort(array);
for(i=0;i<SIZE;i++)
{
printf("%d\n",array[i]);
}
return 0;
}
void selectSort(int * array)
{
int i,j,min,t;
for(i=0;i<SIZE;i++)
{
min=i;
for(j=i+1;j<SIZE;j++)
{
if(array[min]>array[j])
{
min=j;
}
}
if(i!=min)
{
t=array[min];
array[min]=array[i];
array[i]=t;
}
}
}
直接插入排序:----------------------------------------------------------------------
#include<stdio.h>
#define SIZE 8
void insertSort(int *array);
int main()
{
int array[SIZE] = {3,4,1,6,-1,0,9,8};
int i;
insertSort(array);
for(i=0;i<SIZE;i++)
{
printf("%d\n",array[i]);
}
return 0;
}
void insertSort(int *array)
{
int i,j;//i代表未排序的数据指针,j代表已排序的数据指针
int t;
for(i=1;i<SIZE;i++)
{
for(j=i;j>=0;j--)//i指针之前的数据已经有序
{
if(array[j]<array[j-1])//把i指针指向的数据插入i之前的集合中
{
t=array[j-1];
array[j-1]=array[j];
array[j]=t;
}
}
}
}
快排-------------------------------------------------------------------------------
#include<stdio.h>
void quickSort(int *array,int low,int high);
int findPos(int *array,int low,int high);
int main()
{
int i;
int array[6] = {8,9,3,0,4,5};
quickSort(array,0,5);
for(i=0;i<6;i++)
{
printf("%d\n",array[i]);
}
return 0;
}
void quickSort(int *array,int low,int high)
{
int pos;
if(low < high)
{
pos = findPos(array,low,high);
// printf("%d\n",pos);
quickSort(array,low,pos-1);
quickSort(array,pos+1,high);
}
}
int findPos(int *array,int low,int high)
{
int value = array[low];
while(low<high)
{
while(low<high && value<=array[high]) //high指针所指的数据比value大的且high指针不等于low指针,high指针向左移
{
high--;
}
array[low] = array[high];//high指针所指的数据比value小的,直接向左赋值
while(low<high && value>=array[low])//low指针所指的数据比value小的且high指针不等于low指针,low指针向右移
{
low++;
}
array[high] = array[low];//low指针所指的数据比value大的,直接向右赋值。
}
array[low] = value;
return high;
}
这篇关于数据结构之排序(冒泡,选择,插入,快排)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!