# In C++: Use a rand() function (seeded with srand(time(0))) to generate a small arrays of dimensions 20, such that the entries are random positive integers less than 100. Implement the bubble sort and the selection sort and sort your random array of integers.

Question

In C++:

Use a rand() function (seeded with srand(time(0))) to generate a small arrays of dimensions 20, such that the entries are random positive integers less than 100. Implement the bubble sort and the selection sort and sort your random array of integers.

check_circle

Step 1

Program Algorithm-

START

Step2: Define the main function.

Step3: Declare all the variables and their datatypes accordingly.

Step4: Define the arrays and their size.

Step5: Use rand() function to insert random values in the array.

Step6: Use for loop to input the elements in each iteration.

Step7: Define two functions for implementing the logic of Bubble sorting and Selection Sorting.

Step8: Call both the function simultaneously.

Step9: Use another for loop to print the sorted elements of the array.

END

Step 2

Here in this program we have used the concept of pointers which eventually helped in reducing the complexity of program. Pointers store address of variables or a memory location. Pointer execution time is faster because the address is used to manipulate the data, i.e. direct access to the location of the memory.

Syntax for pointers-

datatype *var_name;

int *ptr;

Code(in C++)-

#include <iostream>

using namespace std;

//swap function

void swap(int *xp, int *yp)

{

//Swapping is performed

int temp = *xp;

*xp = *yp;

*yp = temp;

}

// A function to implement bubble sort

void bubbleSort(int arr[], int n)

{

int i, j;

for (i = 0; i < n-1; i++)

// Last i elements are already in place

for (j = 0; j < n-i-1; j++)

if (arr[j] > arr[j+1])

swap(&arr[j], &arr[j+1]);

}

// Implementing Selection sort using function

void selectionSort(int arr[], int n)

{

int i, j, min_idx;

// One by one move boundary of unsorted subarray

for (i = 0; i < n-1; i++)

{

// Find the minimum element in unsorted array

min_idx = i;

for (j = i+1; j < n; j++)

if (arr[j] < arr[min_idx])

min_idx = j;

// Swap the found minimum element with the first element

swap(&arr[min_idx], &arr[i]);

}

}

/* Function to print an array */

void printArray(int arr[], int size)

{

int i;

for (i = 0; i < size; i++)

cout << arr[i] << " ";

cout << endl;

}

// main function

int main()

{

int i, j, n=20, temp;

...

### Want to see the full answer?

See Solution

#### Want to see this answer and more?

Solutions are written by subject experts who are available 24/7. Questions are typically answered within 1 hour.*

See Solution
*Response times may vary by subject and question.
Tagged in

### Computer Science 