vc++ generate random via random_device and uniform_int_distribution

// ConsoleApplication3.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <random>  
using namespace std; 

void getArray(int* arr, int len);
void swap(int* left, int* right);
int partitionAsc(int* arr, int low, int high);
void quickSortAsc(int* arr, int low, int high);
void printArray(int* arr, int len);
void arrayDemo(int len);

int main(int args,char **argv)
{
    arrayDemo(atoi(argv[1]));
}


void arrayDemo(int len)
{
    int* arr = new int[len];
    getArray(arr, len);
    cout << "Before quick sort:" << endl;
    printArray(arr, len);
    cout << "After quick sort:" << endl;
    quickSortAsc(arr, 0, len - 1);
    printArray(arr, len);
    delete[] arr;
    cout << "Finished in void arrayDemo(int len)!" << endl;
}

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


void quickSortAsc(int* arr, int low, int high)
{
    if (low < high)
    {
        int pivot = partitionAsc(arr, low, high);
        quickSortAsc(arr, low, pivot - 1);
        quickSortAsc(arr, pivot + 1, high);
    }
}

int partitionAsc(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 swap(int* left, int* right)
{
    int temp = *left;
    *left = *right;
    *right = temp;
}

void getArray(int* arr, int len)
{
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dist(1, 2147483647);
    for (int i = 0;i < len;i++)
    {
        arr[i] = dist(gen);
    }
}
 
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu

// Tips for Getting Started: 
//   1. Use the Solution Explorer window to add/manage files
//   2. Use the Team Explorer window to connect to source control
//   3. Use the Output window to see build output and other messages
//   4. Use the Error List window to view errors
//   5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
//   6. In the future, to open this project again, go to File > Open > Project and select the .sln file

 

Build via Visual studio 2022 command and run in terminal as below.

.\ConsoleApplication3.exe 100;

 

Snapshot

 

posted @ 2022-08-10 00:09  FredGrit  阅读(24)  评论(0编辑  收藏  举报