I was wondering if someone could help me out finding the Big-O of these two functions:
This function I'm guessing is O(1) but I'm thinking that's wrong.
1 2 3 4 5 6
int sum(int A[], int i, int n) {
if (n == 1)
return A[i];
return sum(A, i, n/2) + sum(A, i + n/2, (n+1)/2);
}
I need the Big-O of the sort function for this one: I'm guessing it's O(n)?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
void swapMin(int A[], constint& index) {
int indexMin = index;
for (int i = index-1; i >= 0; --i)
if (A[i] < A[indexMin])
indexMin = i;
swap(A[index], A[indexMin]);
}
void sort(int A[], int n) {
for (int i = n-1; i >= 0; --i)
swapMin(A, i);
}
Also, could someone tell me the output of this, using the above functions:
1 2 3 4 5 6 7 8 9 10
int main() {
int a[4] = {5, 3, 2, 7};
sort(a, 4);
for (int i = 0; i < 4; ++i)
cout << a[i] << " ";
return 0;
}
#include <iostream>
usingnamespace std;
int count = 0; // Note
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
void swapMin(int A[], constint& index) {
int indexMin = index;
for (int i = index-1; i >= 0; --i)
{
++count; // Note
if (A[i] < A[indexMin])
indexMin = i;
}
swap(A[index], A[indexMin]);
}
void sort(int A[], int n) {
for (int i = n-1; i >= 0; --i)
swapMin(A, i);
}
int main() {
int a[4] = {5, 3, 2, 7};
sort(a, 4);
for (int i = 0; i < 4; ++i)
cout << a[i] << " ";
cout << endl << "count = " << count << endl; // Note
return 0;
}
Try this for different sizes of the array a (5,6,7,8...)
You will see that the value of count will follow a certain schematic. Tip: How many 4/2, 5/2, ... n/2 are there?
And no it's not O(n) (EDIT: it's (n2 - n) / 2)