C++ selection sort.quick sort

void Util::getArray23(int *arr, int len)
{
    srand(time(NULL));
    for (int i = 0; i < len; i++)
    {
        arr[i] = rand();
    }
}

void Util::printArray24(int *arr, int len)
{
    for (int i = 0; i < len; i++)
    {
        cout << arr[i] << "\t";
    }
    cout << endl
         << endl;
}

void Util::selectionSort(int *arr, int len)
{
    for (int i = 0; i < len; i++)
    {
        int minIndex = i;
        for (int j = i + 1; j < len; j++)
        {
            if (arr[j] < arr[minIndex])
            {
                minIndex = j;
            }
        }
        if (i != minIndex)
        {
            swap(&arr[i], &arr[minIndex]);
        }
    }
}

void Util::swap(int *left, int *right)
{
    int temp = *left;
    *left = *right;
    *right = temp;
}

void Util::array26(int len)
{
    int *arr = new int[len];
    getArray23(arr, len);
    cout << "Before selection sort:" << endl;
    printArray24(arr, len);
    cout << "After selection sort:" << endl;
    selectionSort(arr, len);
    printArray24(arr, len);
    delete[] arr;
    cout << "Finished in void Util::array26(int len) and now is " << getTimeNow() << endl;
}

 

 

 

 

Quick sort

int Util::partition28(int *arr,int low,int high)
{
    int pivot=arr[high];
    int i=low-1;
    for(int j=low;j<high;j++)
    {
        if(arr[j]<pivot)
        {
            i=i+1;
            swap(&arr[i],&arr[j]);
        }
    }
    swap(&arr[i+1],&arr[high]);
    return i+1;
}

void Util::quickSort27(int *arr,int low,int high)
{
    if(low<high)
    {
        int pivot=partition28(arr,low,high);
        quickSort27(arr,low,pivot-1);
        quickSort27(arr,pivot+1,high);
    }
}


void Util::array29(int len)
{
    int *arr = new int[len];
    getArray23(arr, len);
    cout << "Before quick sort:" << endl;
    printArray24(arr, len);
    cout << "After quick sort:" << endl;
    quickSort27(arr, 0, len - 1);
    printArray24(arr, len);
    delete[] arr;
    cout << "Finished in void Util::array29(int len) and now is " << getTimeNow() << endl;
}

 

 

 

 

posted @ 2022-03-19 17:05  FredGrit  阅读(17)  评论(0编辑  收藏  举报