Jackson Ramirez
Jackson Ramirez

Reputation: 177

Insertion sort not printing all values in C

Insertion sort is not working, it is only printing some of the values. Does anyone know what I can do to fix it?

void insertion(int Array[], int n) {
   for (int i = 1; i < n; i++) {
      int j = i;
      while (j >= 0 && Array[j] < Array[j - 1]) {
         int temp = Array[j];
         Array[j] = Array[j - 1];
         Array[j - 1] = temp;
         j--;
      }
   }
}

Upvotes: 0

Views: 95

Answers (2)

user607464
user607464

Reputation: 23

Insertion Sort: Idea  Similar to how most people arrange a hand of poker cards Start with one card in your hand Pick the next card and insert it into its proper sorted order Repeat previous step for all cards enter image description here

Upvotes: 0

chqrlie
chqrlie

Reputation: 144923

The test in the inner loop is incorrect: when j == 0 you read and possibly modify the element at offset -1, which has undefined behavior, possibly causing the incorrect output, but since you did not post the output code, there might be other problems there.

Here is a modified version:

void insertion(int Array[], int n) {
    for (int i = 1; i < n; i++) {
        for (int j = i; j > 0 && Array[j] < Array[j - 1]; j--) {
            int temp = Array[j];
            Array[j] = Array[j - 1];
            Array[j - 1] = temp;
        }
    }
}

Upvotes: 1

Related Questions