Click here to Skip to main content
15,868,141 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Why paragraph j=j-1
then down again arr[j +1] = key
I think if I change the number 1 with another number, it will not change but why when I change it, the result changes?



// C program for insertion sort
#include <stdio.h>

/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
	int i, key, j;
	for (i = 1; i < n; i++) {
		key = arr[i];
		j = i - 1;

		/* Move elements of arr[0..i-1], that are
		greater than key, to one position ahead
		of their current position */
		while (j >= 0 && arr[j] > key) {
			arr[j + 1] = arr[j];
			j = j - 1;
		}
		arr[j +1] = key;
	}
}

// A utility function to print an array of size n
void printArray(int arr[], int n)
{
	int i;
	for (i = 0; i < n; i++)
		printf("%d ", arr[i]);
	printf("\n");
}

/* Driver program to test insertion sort */
int main()
{
	int arr[] = { 12, 11, 13, 5, 6 };
	int n = sizeof(arr) / sizeof(arr[0]);

	insertionSort(arr, n);
	printArray(arr, n);

	return 0;
}


What I have tried:

i don't understand why when i tried to change number 1 to other number, the result changed
Posted
Updated 2-Dec-22 23:34pm

1 solution

Think about it: what did you expect it to do? If you could change the number 1 to say 43 and get no change in the results, then adding any number is irrelevant, and that is surely not the case.

Look at "your" code:
C
while (j >= 0 && arr[j] > key) {
			arr[j + 1] = arr[j];
			j = j - 1;
		}
		arr[j +1] = key;
It's a loop, which iterates until either j is negative, or the array element at index j is less than or equal to the value in key
So you need something inside the loop to alter the value of j, or key, or both.
Since you don't want key to alter, j much change or the loop will continue forever.
And that's what this like does:
C
j = j - 1;
It subtracts one from the current value of j and stores the result back into j.
If you changed the value in this line from 1 to 43 then it would loop round a lot fewer times, and look at a lot fewer array elements!
(It can be written shorter:
C
j--;
does exactly the same thing.)

The other line inside the loop is simpler: it's "moving" each element of the array into the element above it.

Try it on paper and you'll see what I mean.
 
Share this answer
 
Comments
i want to code better 3-Dec-22 9:06am    
I really appreciate you for the answer.
Thank you so much!
OriginalGriff 3-Dec-22 10:47am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900