0
Snippet:

//c is swap counter , while j is for optimisation  

for( int c= -1, j = 0 ; c != 0 ; )         //loop till c==0
    {
        c = 0;  
        for(int i = 0 ; i < (6-j) ; i++)   //7 elements have to be sorted
        {
            int element = values[i];       // swapping

            if (element > values[i+1])
            {               
            c++;
            values[i] = values[i+1];
            values[i+1] = element;
            }

            if(i == 5-j)       // increment j at last iteration everytime
            j=j+1;
        }
    }

Is more efficient code possible?

1
  • It is hard to say about efficiency. Offcourse there is always a possibility to improve the code but you have to decide which Efficiency do you want. Memory efficient or time efficient? May be you can calculate the execution time of your algorithm and then compare it with another one for better learning. You have to have a baseline for comparison of Efficiency.
    – Wafeeq
    Jun 27 '16 at 8:15
-1

Firstly, this solution is hard-coded for 7 elements. Secondly, you don't need so many variables. Consider, as a method:

    static int[] Bubblesort(int[] unsorted)
    {
        for (int i = 0; i < unsorted.Length; i++)
        {
            for (int j = 0; j < unsorted.Length; j++)
            {
                if (unsorted[i] < unsorted[j])
                {
                    int temp = unsorted[i];
                    unsorted[i] = unsorted[j];
                    unsorted[j] = temp;
                }
            }
        }
        return unsorted;
    }

Efficiency is important but so is keeping your code succinct and easy to read.

1
  • I find ur code wrong plz verify
    – taichouvik
    Jun 29 '16 at 9:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .