문제

For an insertion sort to order strings, I'm having issues with strcpy properly updating temp, Ai, and Aj...

for (int j = 1; j < m; j++) {
   int i = j - 1;
   char temp[MAX_LEN]; //= arrayIn[j];
   char Ai[MAX_LEN];
   char Aj[MAX_LEN];

   strcpy(temp,arrayIn[j]);
   strcpy(Ai,arrayIn[i]);
   strcpy(Aj,arrayIn[j]);

   while (i >= 0 && strcmp (Ai, temp) < 0 /* Aj < Ai */) {
      arrayIn[i+1] = arrayIn[i];
      i = i - 1;
   }

   arrayIn[i+1] = temp;
}

Sample output:

Input:

array[0]:    one
array[1]:    two
array[2]:    three
array[3]:    four
array[4]:    five

Output:

array[0]:    five
array[1]:    five   
array[2]:    one
array[3]:    five
array[4]:    five

Desired Output:

array[0]:    five
array[1]:    for
array[2]:    one
array[3]:    three
array[4]:    two
도움이 되었습니까?

해결책

If you are going to use strcpy, you have to use it thoughout:

for (int j = 1; j < m; j++) {
   int i = j - 1;
   char temp[MAX_LEN];

   strcpy(temp, arrayIn[j]);

   while (i >= 0 && strcmp (arrayIn[i], temp) < 0) {
      strcpy(arrayIn[i+1], arrayIn[i]);
      i = i - 1;
   }

   strcpy(arrayIn[i+1], temp);
}

This works if your array is an array of char arrays as in your case. If you have an array of pointers to char, you can write your sort with assignments just as for integers:

for (int j = 1; j < m; j++) {
   int i = j - 1;
   char *temp;

   temp = arrayIn[j];

   while (i >= 0 && strcmp(arrayIn[i], temp) < 0) {
      arrayIn[i+1] = arrayIn[i];
      i = i - 1;
   }

   arrayIn[i+1] = temp;
}

The sorting condition must still be checked with strcmp, however. Note that in the second case, the pointers may point to constant immutable strings.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top