1. 程式人生 > >分組排序和氣泡排序

分組排序和氣泡排序

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
 
void groupSort()
{
        srand(unsigned(time(NULL)));
        int size =rand()%20;
        int* arr=new int[size];
        for(int i=0;i<size;++i)
        {
            arr[i]=rand()%100;
        }
        cout<<"before sort"<<endl;
        for(int i=0;i<size;++i)
        {
            cout<<arr[i]<<"\t";
        }
        for(int i=0;i<size-1;++i)
        {
            int k=i;
            for(int j=i+1;j<size;++j)
            {
                if(arr[k]>arr[j])
                {
                    k=j;
                }
            }
            if(k!=i)
            {
                int temp=arr[k];
                arr[k]=arr[i];
                arr[i]=temp;
            }
        }
        cout<<endl<<"after sort"<<endl;
        for(int i=0;i<size;++i)
        {
            cout<<arr[i]<<"\t";
        }
        delete []arr;
 
}
 
void bubbleSort()
{
    srand(unsigned(time(NULL)));
    int size=rand()%20;
    int* arr=new int[size];
    for(int i=0;i<size;++i)
    {
        arr[i]=rand()%100;
    }
    cout<<"before bubblesort"<<endl;
    for(int i=0;i<size;++i)
    {
        cout<<arr[i]<<"\t";
    }
    cout<<endl;
    for(int i=0;i<size-1;++i)
    {
        bool isright=true;
        for(int j=0;j<size-1-i;++j)
        {
            if(arr[j]>arr[j+1])
            {
                isright=false;
                int temp=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
            }
        }
        if(isright)
        {
            break;
        }
    }
    cout<<"after bubblesort"<<endl;
    for(int i=0;i<size;++i)
    {
        cout<<arr[i]<<"\t";
    }
    delete []arr;
}
 
void main()
{
    //groupSort();
    //bubbleSort();
	int a;
	cin>>a;
    
}