Algorithm for sorting an array of pointers in C ++

I hope that I get a little advice on the sorting method that I did.

This is just a test for another program that I am doing, and this test has an error that I cannot understand. The purpose of this code is to create an array of int pointers and sort the pointers in this array by the contents of the regular int array.

An error for my second loop cycle that prevents me from using j! = -1, so it does not allow sorting the first element of the array. Please help. Thanks!!

//create array int c[8] = {3,1,5,7,8,2,6,4}; //create pointer array int *newptr[8]; for(int k = 0; k<8; k++) { newptr[k] = &c[k]; } //sort pointer array for(int j = 0; j<8; j++) { cout << "test1\n\n"; cout << *newptr[j] << "and" << *newptr[j+1]; for(;*newptr[j] < *newptr[j+1] && j!=0; j--) //using j!=-1 doesn't work which causes me to not be able to sort the first element //in the array properly { cout<< "test2"; int *temp; temp = newptr[j+1]; newptr[j+1] = newptr[j]; newptr[j] = temp; } }** 
+4
source share
2 answers

Questions for the order.

Edit

 for(;*newptr[j] < *newptr[j+1] && j!=0; j--) 

in

 for(; j != -1 && *newptr[j] < *newptr[j+1]; j--) 

Presumably an error is what causes the code to crash. This is because the expression in the for loop evaluates from left to right. Therefore, *newptr[j] is evaluated to if j != -1 . Therefore, we can assume that at some point j is -1 when *newptr[j] is evaluated, which is illegal.

Reordering matters for a second reason: short circuit assessment .

When evaluating two expressions made from two conditions A and B , C ++ does not always need to evaluate both conditions.

For example, in a statement

 if (A && B) { //do something } 

if A evaluates to false , then obviously A && B cannot evaluate to true no matter what evaluates to B Therefore, the value of B never checked. So, in your case, in the expression

 j != -1 && *newptr[j] < *newptr[j+1] 

if j != -1 is false, C ++ does not need to evaluate the rest of the expression to know that the whole expression is false. So *newptr[j] never happens, and you don't get an error.

+8
source

As maditya pointed out, the problem is that the expression is trying to access an invalid index before checking the index itself, but I see that the question is marked as C ++. Do you have a clear reason not to use STL?

 struct sorter { bool operator() (const int* i, const int* j) { return (*i<*j);} }; int c[8] = {3,1,5,7,8,2,6,4}; int *newptr[8]; for(int k = 0; k<8; k++) newptr[k] = &c[k]; std::sort(newptr, newptr+8, sorter()); 

or even shorter in C ++ 11:

 int c[8] = {3,1,5,7,8,2,6,4}; int *newptr[8]; for(int k = 0; k<8; k++) newptr[k] = &c[k]; std::sort(newptr, newptr+8, [](const int *i, const int *j){return *i < *j;}); 
+5
source

Source: https://habr.com/ru/post/1495261/


All Articles