Question 2 - 3 Functions

 avatar
itsLu
c_cpp
a year ago
1.8 kB
46
Indexable
/* 2. Write 3 functions to: generate 20 unrepeated random numbers with values
 between 30 and 80, sort these numbers using bubble sort algorithm, and and print
 the numbers after sorting. Write a main program to call these 3 functions. */

#include <iostream>
#include <ctime> //or <time.h>
#include <random> //مش مهمة بس الدكتور بيحطها
using namespace std;

void fillArray (int arr[], int minNum, int maxNum, int arraySize)
{
    int temp, k, p;
    bool flag;
    srand(time(NULL)); //or srand(time(0));
    for (k = 0 ; k < arraySize ; k++)
    {
        flag = false;
        temp = minNum + rand()%(maxNum - minNum + 1);
        for (p = 0 ; p < k ; p++)
        {
            if (arr[p] == temp)
            {
                flag = true;
                break;
            }
        }
        if (flag == false)
            arr[k] = temp;
        else
            k--;
        /* or
        if (p == k)
            arr[k] = temp;
        else
            k--;
        */
    }
}

void bubble_sort (int arr[], int arraySize)
{
    int temp;
    bool flag;
    for (int p = 0 ; p < arraySize - 1 ; p++)
    {
        flag = false;
        for (int c = 0 ; c < arraySize - p - 1 ; c++)
        {
            if (arr[c] > arr[c+1])
            {
                temp = arr[c];
                arr[c] = arr[c+1];
                arr[c+1] = temp;
                flag = true;
            }
        }
        if (flag == false)
            break;
    }
}

void printArray (int arr[], int arraySize)
{
    for (int k = 0 ; k < arraySize ; k++)
    {
        cout << arr[k] << "\t";
    }
}

int main()
{
    int arr[20];
    fillArray(arr, 30, 80, 20);
    printArray(arr, 20);
    cout << endl;
    bubble_sort(arr, 20);
    printArray(arr, 20);
}
Editor is loading...
Leave a Comment