I'm trying to count the number of correct (sorted) positions in an array.
example:
Code:
1 2 3 4 5 6 7 8 9 10
10 positions are correct.
example2:
Code:
1 2 3 4 5 6 7 8 9 0
9 positions are correct.
example3:
Code:
10 9 8 7 6 5 4 3 2 1
0 positions are correct.
example4:
Code:
10 9 8 7 6 5 4 3 2 15
1 positions are correct.
The code i'm using now for this doesn't work:
Code:
#include <iostream>
using namespace std;
int PickBestSort(int array1[], int size);
int PrintArray(int array1[], int size);
int main()
{
int array1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int array2[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int size = 10;
PickBestSort(array1, size);
PrintArray(array1, size);
cout << endl;
return 0;
}
int PickBestSort(int array1[], int size)
{
float percentSorted = 0;
for(int i = 0; i < (size-1) ; i++)
{
//Checks how sorted the array is. The higher "percentSorted" is, the more sorted the array is.
if (array1[i] <= array1[i+1])
{
percentSorted++;
}
}
cout << endl << "Percent Sorted: " << percentSorted*10 << endl;
cout << endl << percentSorted << " out of " << size << " positions are correct." << endl;
//If 20% or less of the array is sorted, then it is considered to be reverse sorted.
if ( percentSorted <= 20)
{
cout << endl << "The array is reverse sorted or close to being reverse sorted." << endl;
}
//If 80% or more of the array is sorted, then it is considered to be already sorted.
else if ( percentSorted >= 80)
{
cout << endl << "The array is already sorted or close to being already sorted." << endl;
}
//If between 20% and 80% of the array is sorted, then it is considered to be random.
else
{
cout << endl << "The array is random or close to being random." << endl;
}
return 0;
}
int PrintArray(int array1[], int size)
{
cout << endl;
for (int j = 0; j < size; j++)
{
cout << array1[j];
cout << " ";
}
return 0;
}
So, my counting algorithm (in red) increases by one, if a value is less than the value in front of it.
Right now, in example 1, my program will only say 9 positions are correct, instead of 10. This is because the last value in the array isn't compared to anything. However, examples 3 and 4 will read correctly. If if change the algorithm to where examples 1 and 2 work, then 3 and 4 won't work (they will say one more position is correct than really is). I can't figure out a counting algorithm that will work for all cases.
I am only suppose to run through the array once to analyze it, and i can't change the array, because it will mess up the sorting algorithm later on in the program, and i don't think i'm suppose to change the array once the numbers are read into it.
If you are wondering, my program is suppose to analyze an array, and choose a sorting algorithm based on efficiency. I'm trying to determine how sorted the array is, so i can best choose the most efficient sort.
Any ideas?
Thanks.