# Sorting algorithms (Lecture 2)

Sameh
c_cpp
2 months ago
3.6 kB
82
Indexable
Never
```#include <iostream>
#include <ctime>

using namespace std;

void generateRandomNumbers(int *a , int n , int max = 101)
{
srand(time(NULL));
for(int i = 0 ; i < n ; i++)
{
a[i] = rand() % max ;
}
}

void selectionSortAlgorithmWithDebugging(int *a , int n)
{
int temp;
for (int i = 0; i < n - 1; i++)
{
cout << "Outer Iteration  : " << i+1 << "\n";
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
cout << "Inner Iteration : " << j-i << "\n";
for(int k = 0 ; k < n ; k++)
{
cout << a[k] << "\t";
}
cout << "\n";
}
}
}

void bubbleSortAlgorithmWithDebugging(int *a , int n)
{
int temp;
for (int i = 0 ; i < n - 1 ; i++)
{
cout << "Outer Iteration  : " << i+1 << "\n";
for(int j = 0 ; j < n - i - 1 ; j++)
{
if(a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
cout << "Inner Iteration : " << j+1 << "\n";
for(int k = 0 ; k < n ; k++)
{
cout << a[k] << "\t";
}
cout << "\n";
}
}
}

void insertionSortAlgorithmWithDebugging(int *a , int n)
{
int temp , j;
for (int i = 1 ; i < n ; i++)
{
temp = a[i];
j = i - 1;
cout << "Outer Iteration : " << i << "\n";
while(j >= 0 && a[j] > temp)
{
a[j + 1] = a[j];
j--;
a[j+1] = temp;
cout << "Inner Iteration : " << i-j-1 << "\n";
for(int k = 0 ; k < n ; k++)
{
cout << a[k] << "\t";
}
cout << "\n";
}
}
}

void selectionSortAlgorithmWithoutDebugging(int *a , int n)
{
int temp;
for (int i = 0; i < n - 1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}

void bubbleSortAlgorithmWithoutDebugging(int *a , int n)
{
int temp;
for (int i = 0 ; i < n - 1 ; i++)
{
for(int j = 0 ; j < n - i - 1 ; j++)
{
if(a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}

void insertionSortAlgorithmWithoutDebugging(int *a , int n)
{
int temp , j;
for (int i = 1 ; i < n ; i++)
{
temp = a[i];
j = i - 1;
while(j >= 0 && a[j] > temp)
{
a[j + 1] = a[j];
j--;
}
a[j+1] = temp;
}
}

void mergeSort()
{
//هههه ضحكت عليك مفيش كود ولا حاجة ودلوقتي شوف حد يفهمنا الmerge sort
}

int main()
{
int arr[5] , originalArr[5];

generateRandomNumbers(arr , 5);
for(int i = 0 ; i < 5 ; i++)
{
cout << arr[i] << "\t";
originalArr[i] = arr[i];
}
cout << "\n";

selectionSortAlgorithmWithoutDebugging(arr , 5);
for(int i = 0 ; i < 5 ; i++)
{
cout << arr[i] << "\t";
}
cout << "\n\n";

selectionSortAlgorithmWithDebugging(originalArr , 5);

return 0;
}```