- #include <iostream>
- #include <fstream>
- #include <time.h>
- using namespace std;
- #define TXT_NUM_COUNT 1000001
- int ImportToArray(const char *filename,int *array) //将filename内的纯数字文本导入数组array;
- {
- int count=0;
- ifstream fin;
- fin.open(filename);
- if( fin.fail() )
- {
- cout<<"file read fail!"<<endl;
- return -1;
- }
- while( fin.eof() ==false )
- fin>>array[count++];
- fin.close();
- return count;
- }
- int ExportWithArray(const char *filename,int *array,int count)
- {
- ofstream fout;
- fout.open(filename);
- if(fout.fail())
- {
- cout<<"file wirte fail"<<endl;
- return -1;
- }
- for(int i=0;i<count;i++)
- fout<<array[i]<<endl;
- fout.close();
- }
- void bubbleSort(int *array,int count) //冒泡排序法
- {
- int t;
- for(int i=0;i<count-1;i++)
- {
- for(int j=0;j<(count-i-1);j++)
- if(array[j]>array[j+1])
- {
- /*array[j]=array[j]^array[j+1];
- array[j+1]=array[j]^array[j+1];
- array[j]=array[j]^array[j+1]; */
- t=array[j];
- array[j]=array[j+1];
- array[j+1]=t;
- }
- cout<<i<<endl;
- }
- }
- void merge(int *left,int lsize,int *right,int rsize) //来自wiki百科
- {
- int i,j,k;
- i=j=k=0;
- int *TempArray=new int[lsize+rsize];
- while(i<lsize && j<rsize)
- {
- //较小的数据放到临时数组
- TempArray[k++]=left[i]<right[j] ? left[i++] : right[j++];
- }
- //把剩下的元素复制到临时数组
- while (i<lsize)
- TempArray[k++]=left[i++];
- while (j<rsize)
- TempArray[k++]=right[j++];
- //将临时数组放到left,即原数组的最左边
- for(int g=0;g<(lsize+rsize);g++)
- left[g]=TempArray[g];
- delete [] TempArray; //销毁临时数组
- }
- void mergeSort(int *array,int size) //来自wiki百科
- {
- if (size>1)
- {
- int *left=array;
- int left_size=size/2;
- int *right=array+size/2;
- int right_size=size-left_size;
- mergeSort(left,left_size);
- mergeSort(right,right_size);
- merge(left,left_size,right,right_size);
- }
- }
- void main()
- {
- time_t t_start,t_end;
- int *array=new int[TXT_NUM_COUNT]; //已经测得有1000001个数据,其中多测一个为空行
- int count=ImportToArray("largeW.txt",array);
- //printf("%d %d",count,array[count-1]);
- cout<<count<<" "<<array[count-1]<<endl;
- t_start=time(NULL);
- // bubbleSort(array,count-1);
- mergeSort(array,count-1);
- t_end=time(NULL);
- // cout<<"冒泡用时(S):"<<difftime(t_end,t_start)<<endl;
- cout<<"归并用时(S):"<<difftime(t_end,t_start)<<endl;
- // ExportWithArray("largeW_bubble.txt",array,count-1);
- ExportWithArray("largeW_merge.txt",array,count-1);
- delete [] array;
- // 测试用
- //int a[]={8,2,1,4,6,8,9,0,1,1};
- bubbleSort(a,10);
- //mergeSort(a,10);
- //ExportWithArray("test.txt",a,10);
- //for(int i=0;i<10;i++)
- // cout<<a[i]<<" ";
- }
第三周作业——冒泡排序和归并排序
最新推荐文章于 2019-08-29 09:17:33 发布