I think the best first step to finding the bug is to simplify the code as much as possible. In the large loop, I think the variable j is redundant, because it's always equal to i-1. Removing it will make it easier to find the problem.
Second, both i, j and k is not needed outside the scopes where they are used. You should try to have them declared in the closest scope possible. This means:
1 2 3 4 5 6 7
|
// Remove this line:
int i, k, j = 1;
// Change the for loops to:
for (int i = ...
// Declare k where you first need it:
int k = i - 1;
// Remove j entirely
|
Doing these changes helps me figure out your code, and understanding what you're trying to do. It is basically the well known algorithm called insertion sort. Instead of sorting the array in place, you sort an array of references (O) to the original array, and you need a third array to temporary save your sorted array, so that you don't overwrite anything. You should know that it is possible to do the same thing with only one array. You simply have to do everything you do with O with p instead in the large loop.
Now to the actual problem: what if p[i] is the smallest value in the array in the inner while loop? You should try changing it to:
|
while (p[O[k]]>p[i] && k > 0)
|
I have a couple of other comments for you:
I don't like the (nothrow) and error handling using goto. You basically disable the much better error handling in C++, and go back to using old fashioned C code. If you really need to handle memory problems with NOT sorting the array (you will probably crash anyway), you should use a try...catch block, which is exactly what you simulate using the goto.
I don't like your indenting. You should stick with what's commonly used, and don't try to be overcreative. Get an editor with support for automatic indenting, and don't try to reinvent the wheel.
If you really only need to implement this sorting algorithm, you should do a search for insertion sort, and find examples of how to sort the array in place.
If you only need to sort an array, you should simply write:
|
std::sort(array, array + d);
|
But of course it's more interesting to implement it yourself, and you learn a lot in the process.
I wish you good luck.