I'm doing some simple algorithm analysis atm. Though I'm not sure if I'm getting all the right stuff down. Here's the code that my professor showed us of the selection sort:
Some minor questions
A) How do I assign all the elements at once of a dynamically created array?
B) Does every single array access count? The if statement inside the two for loops gets accessed at worst, every single time for n-1 times. In otherwords, working inside out, the if statement gets executed 2(n-1) times?
My professor ended up getting T = 3/2(n^2) +3/2 - 3 as the actual run time of the problem. Now selection sort is very obviously O(n^2) due to the for loops. I'm having trouble determining what actually contributes to running time. AFAIK, every ; signifies 1, and for loops multiply 1 by however many times it must be run.
Code:
#include <iostream>
using namespace std;
int find_Max(int*, int);
void swapElements(int*, int, int);
int main()
{
int n = 10;
int *arr = new int[n];
arr[0] = 8;
arr[1] = 5;
arr[2] = 2;
arr[3] = 6;
arr[4] = 9;
arr[5] = 3;
arr[6] = 1;
arr[7] = 4;
arr[8] = 0;
arr[9] = 6;
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
for(int i = n; i > 0; i--)
{
swapElements(arr, find_Max(arr, i), i-1);
}
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
delete[] arr;
return 0;
}
int find_Max(int *arr, int last)
{
int index = 0;
for(int j = 1; j < last; j++)
{
if(arr[index] < arr[j]) index = j;
}
return index;
}
void swapElements(int *arr, int index, int last)
{
int temp = arr[last];
arr[last] = arr[index];
arr[index] = temp;
}
Some minor questions
A) How do I assign all the elements at once of a dynamically created array?
B) Does every single array access count? The if statement inside the two for loops gets accessed at worst, every single time for n-1 times. In otherwords, working inside out, the if statement gets executed 2(n-1) times?
My professor ended up getting T = 3/2(n^2) +3/2 - 3 as the actual run time of the problem. Now selection sort is very obviously O(n^2) due to the for loops. I'm having trouble determining what actually contributes to running time. AFAIK, every ; signifies 1, and for loops multiply 1 by however many times it must be run.