Click here to Skip to main content
16,012,116 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
using System;
using System.Collections;
using System.Linq;
using System.Text;

namespace Generalsortingcon
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] items = { 60,30,40,20,80};
            int temp=0;
            int n = items.Length;
            for (int i = 0; i <n mode="hold" />            {
                for (int j = i+1; j <n-i;>                {
                    if (items[j] > items[j+1])//  here getting exception
                    {
                        temp = items[j];
                        items[j] = items[j+1];
                        items[j] = temp;
                    }

                }
                Console.WriteLine("values:" + Convert.ToString(items[i]));
               
            }
            
           
            Console.ReadKey();
           
        }
    }
}
Posted
v2
Comments
There are some problems while pasting the code.
Please paste it again.

1 solution

modify your logic like this
C#
int[] items = { 60, 30, 40, 20, 80 };
int temp = 0;
int n = items.Length;
for (int i = 0; i < n; i++)
{
    for (int j = i ; j < n - i - 1; j++)
    {
        if (items[j] > items[j + 1])// here getting exception
        {
            temp = items[j];
            items[j] = items[j + 1];
            items[j+1] = temp;
        }

    }
    //Console.WriteLine("values:" + Convert.ToString(items[i]));

}

for (int i = 0; i < n; i++)
{
    Console.WriteLine("values:" + Convert.ToString(items[i]));
}


The reason you are getting exception is you are trying to compare items[4] with items[5] which doesnot exists....
so you need to restrict you termination condition to n-I-1

and also you need to change the initial value of j ...
 
Share this answer
 
Comments
prasadhp 8-Jul-13 6:06am    
thanks, if i am not using another for loop o/p is unreliable.could you explain why

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