linux centos fedora gcc c 冒泡 插入 大顶堆 排序
1、生成50万个数据,按行从1-500000存到test1.txt文件中
2、打乱50万个数据,按行存到test2.txt文件中
3、使用排序方法进行排序,将结果保存在test3.txt文件中
4、冒泡法排序
bubblesort(array3, NUM_MAX);
5、插入法排序
insertsort(array3, NUM_MAX);
6、大顶堆法排序
heapify_sort(array3, NUM_MAX);
vi txtnum.c
gcc txtnum.c -o a.out
./a.out
原理不解释了,如果数据过大,可以改写为5000,代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#define NUM_MAX 500000
void swap(int arr[], int a, int b)
{
int tmp;
tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
void heapify(int array3[], int n, int i){
if (i >= n)
{
return;
}
int max = i;
int c1 = 2 * i + 1;
int c2 = 2 * i + 2;
if (c1 < n && array3[c1] > array3[max]){
max = c1;
}
if (c2 < n && array3[c2] > array3[max]){
max = c2;
}
if (max != i)
{
swap(array3, max, i);
heapify(array3, n, max);
}
}
void build_heapify(int array3[], int n)
{
int last_node = n - 1;
int parent = (last_node - 1) / 2;
int i;
for (i = parent; i >= 0; i--)
{
heapify(array3, n, i);
}
}
void heapify_sort(int array3[], int n)
{
build_heapify(array3, n);
int tmp = array3[0];
int i;
for (i = n - 1; i >= 0; i--)
{
swap(array3, i, 0);
heapify(array3, i, 0);
}
}
void bubblesort(int *array3 ,int n)
{
int i;
int j;
int temp;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (array3[j] > array3[j + 1])
{
temp = array3[j];
array3[j] = array3[j + 1];
array3[j + 1] = temp;
}
}
}
}
void insertsort(int *array3,int n)
{
int tmp=0;
int i;
int j;
for (i = 1; i < n; i++)
{
tmp=array3[i];
for (j = i - 1;j >= 0; j-- )
{
if(array3[ j ] > tmp )
{
array3[ j + 1]=array3[ j ];
array3[ j ]=tmp;
}
}
}
}
int main( int argc, char *argv[] )
{
int i=0;
int j=0;
int k=0;
int array1[NUM_MAX];
int array2[NUM_MAX];
int array3[NUM_MAX];
int temp;
int randx;
FILE *fp1,*fp2,*fp3;
printf("%d\n",INT_MAX);
fp1 = fopen("test1.txt","w");
for(i=0;i<NUM_MAX;i++)
{
array1[ i ]=i;
array2[ i ]=i;
array3[ i ]=i;
}
for (j=0; j<NUM_MAX;j++)
{
fprintf(fp1,"%d\n",array1[j]);
}
fclose(fp1);
for ( k=0;k< NUM_MAX; k++)
{
randx=rand()%NUM_MAX;
temp=array2[k];
array2[k]=array2[randx];
array2[randx]=temp;
}
fp2 = fopen("test2.txt","w");
for ( k=0;k< NUM_MAX; k++)
{
fprintf(fp2,"%d\n",array2[k]);
}
fclose(fp2);
fp2 = fopen("test2.txt","r");
for ( k=0;k< NUM_MAX; k++)
{
fscanf(fp2,"%d\n",&array3[k]);
}
fclose(fp2);
fp3 = fopen("test3.txt","w");
//bubblesort(array3, NUM_MAX);
//insertsort(array3, NUM_MAX);
heapify_sort(array3, NUM_MAX);
for ( k=0;k< NUM_MAX; k++)
{
fprintf(fp3,"%d\n",array3[k]);
}
fclose(fp3);
}