In: Computer Science
You are working as the software developer and need to identify the best sorting algorithm.
You can pick any two-sorting algorithm. You need to determine which sorting algorithm is the best to sort the array of 10k elements.
Use the following steps to help with your solution:
PLEASE GIVE THUMBS UP, THANKS
OUTPUT SAMPLE :
code:
#include <iostream>
#include<ctime>
#include<stdlib.h>
using namespace std;
void swap(int *xp, int *yp)
{
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]);
}
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// Driver code
int main()
{
int arr1[10000],arr2[10000];
int n =10000;
int num;
int start_s;
int stop_s;
//generating 10k Randoms numbers
for(int i=0; i<n; i++)
{
num=rand();
arr1[i]=num;
arr2[i]=num;
}
//starting clock for bubble sort
start_s=clock();
bubbleSort(arr1, n);
//stopping cock for bubble sort
stop_s=clock();
cout << "Bubble sort taking time: " <<
(stop_s-start_s)<<"ms" << endl;
//starting clock for insertion sort
start_s=clock();
insertionSort(arr2,n);
//stopping cock for insertion sort
stop_s=clock();
cout << "insertion sort taking time: " <<
(stop_s-start_s)<<"ms" << endl;
return 0;
}