user3182041
user3182041

Reputation:

Insertion sort code not working

Here is the method I have made for insertion sort:

private int i, j, temp;

public void InsertionSort(int[] a)
{
    for(i=0 ; i<a.Length-1 ; i++)
    {
        for(j=i+1 ; j<1 ; j--)
        {
            if(a[j-1]>a[j])
            {
                temp = a[j];
                a[j] = a[j - 1];
                a[j - 1] = temp;
            }
            else
            {
                break; 
            }
        }
    }

It is not sorting the array , when i stepped into the code i saw that the the code inside the inner for loop is not running and the code inside is being constantly surpassed.

for example take the array to be int[] arr = {7,2,3,6,} ;

Upvotes: 0

Views: 89

Answers (1)

Grantly
Grantly

Reputation: 2556

In your code, you have j=i+1 ; j < 1 .... where j< 1 is your condition... This can never be TRUE when j=i+1 as your i starts at zero....I think you want j>1 in your condition

Upvotes: 2

Related Questions