文件文本排序:
数组冒泡:
#include<stdio.h>void swap(int *a,int *b) {int temp = *a;*a = *b;*b = temp; }void bubble(int *p,int n) {int i;int j;for(i = 0; i < n; i++){for(j = 1; j < n - i; j++){if(p[j - 1] > p[j]){swap(&p[j-1],&p[j]);}}} }int main() {int arr[10] = {4,6,3,7,8,5,12,67,34,56};bubble(arr,10);int i;for(i = 0; i < 10 ; i++){printf("%d ",arr[i]);}printf("\n");return 0; }
文件数据排序
#include<stdio.h> #include<string.h>void swap(int *a,int *b) {int temp = *a;*a = *b;*b = temp; }void bubble(int *p,int n) {int i;int j;for(i = 0; i < n; i++){for(j = 1; j < n - i; j++){if(p[j - 1] > p[j]){swap(&p[j-1],&p[j]);}}} }int main() {int array[10] = {0};int i;char buf[100]; int index = 0;FILE* p =fopen("./file.txt","r");if(NULL == p){printf("error\n");}else{while(!feof(p)){memset(buf,0,sizeof(buf));fgets(buf,sizeof(buf),p);array[index] = atoi(buf);index++;}fclose(p);}index--;bubble(array,index);p = fopen("./b.txt","w");printf("index = %d\n",index);for(i = 0; i < index ; i++){memset(buf,0,sizeof(buf));sprintf(buf,"%d\n",array[i]);fputs(buf,p);//printf("%d ",array[i]); }fclose(p);printf("i = %d\n",i);return 0; }
如果文件数据过大,就不能在栈中建立一个数组,考虑使用堆
#include<stdio.h> #include<string.h> #include<stdlib.h>void swap(int *a,int *b) {int temp = *a;*a = *b;*b = temp; }void bubble(int *p,int n) {int i;int j;for(i = 0; i < n; i++){for(j = 1; j < n - i; j++){if(p[j - 1] > p[j]){swap(&p[j-1],&p[j]);}}} }int main() {int i;char buf[100]; int index = 0;FILE* p =fopen("./file.txt","r");if(NULL == p){printf("error\n");}//else {while(!feof(p)){memset(buf,0,sizeof(buf));fgets(buf,sizeof(buf),p);index++;}fclose(p);}int *array = calloc(sizeof(int),index);index = 0;p =fopen("./file.txt","r");if(NULL == p){printf("error\n");}//else {while(!feof(p)){memset(buf,0,sizeof(buf));fgets(buf,sizeof(buf),p);array[index] = atoi(buf);index++;}fclose(p);}index--;bubble(array,index);p = fopen("./b.txt","w");printf("index = %d\n",index);for(i = 0; i < index ; i++){memset(buf,0,sizeof(buf));sprintf(buf,"%d\n",array[i]);fputs(buf,p);//printf("%d ",array[i]); }fclose(p);printf("i = %d\n",i);return 0; }