Click here to Skip to main content
15,896,269 members
Articles / Programming Languages / C#

Quick Sort Without Recursion

Rate me:
Please Sign up or sign in to vote.
4.92/5 (10 votes)
18 Sep 2008CPOL 85.6K   34   11
Quick Sort Without Recursion

Introduction

I found lots of samples online having quick sort with recursion but didn't find any algorithm having quick sort without recursion. This article will help you understand quick sort without recursion.

Using the Code

The following code shows quick sort without recursion. This has been implemented using stack concept LIFO.

C#
using System;
using System.Collections.Generic;
using System.Text;

namespace QuickSort
{
    class Program
    {
       public static void Main(string[] args)
        {
           
           int[] arr = { 4, 3,2, 1, -1, 99, 12, 33, 99, 10};
            q_sort(ref arr);
            foreach (int i in arr)
           {
               Console.WriteLine(i);
           }
        }

        public static void q_sort(ref int[] input)
        {
            System.Collections.Stack stack = new System.Collections.Stack();
            int pivot;
            int pivotIndex = 0;
            int leftIndex = pivotIndex + 1;
            int rightIndex = input.Length - 1;

            stack.Push(pivotIndex);//Push always with left and right
            stack.Push(rightIndex);

            int leftIndexOfSubSet, rightIndexOfSubset;

            while (stack.Count > 0)
            {
                rightIndexOfSubset = (int)stack.Pop();//pop always with right and left
                leftIndexOfSubSet = (int)stack.Pop();

                leftIndex = leftIndexOfSubSet + 1;
                pivotIndex = leftIndexOfSubSet;
                rightIndex = rightIndexOfSubset;

                pivot = input[pivotIndex];

                if (leftIndex > rightIndex)
                    continue;

                while (leftIndex < rightIndex)
                {
                    while ((leftIndex <= rightIndex) && (input[leftIndex] <= pivot))
                        leftIndex++;	//increment right to find the greater 
				//element than the pivot

                    while ((leftIndex <= rightIndex) && (input[rightIndex] >= pivot))
                        rightIndex--;//decrement right to find the 
				//smaller element than the pivot

                    if (rightIndex >= leftIndex)   //if right index is 
						//greater then only swap
                        SwapElement(ref input, leftIndex, rightIndex);
                }

                if (pivotIndex <= rightIndex)
                    if( input[pivotIndex] > input[rightIndex])
                        SwapElement(ref input, pivotIndex, rightIndex);
               
                if (leftIndexOfSubSet < rightIndex)
                {
                    stack.Push(leftIndexOfSubSet);
                    stack.Push(rightIndex - 1);
                }

                if (rightIndexOfSubset > rightIndex)
                {
                    stack.Push(rightIndex + 1);
                    stack.Push(rightIndexOfSubset);
                }
            }
        }

        private static void SwapElement(ref int[] arr, int left, int right)
        {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
        }
    }
} 

Feel free to ask any questions by emailing me at varun_jain786@yahoo.com or write comments in the forum below.

History

  • 18th September, 2008: Initial post

License

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


Written By
Software Developer (Senior)
United States United States
Sr Developer (Passionate Developer)
varun_jain786@yahoo.com

http://sites.google.com/site/varunjain786main/
http://www.linkedin.com/in/varunjain786

Comments and Discussions

 
GeneralMy vote of 5 Pin
Nanda Mangati15-Aug-13 21:31
professionalNanda Mangati15-Aug-13 21:31 
QuestionHow about this algorithm? Pin
Member 142664114-Aug-13 9:24
Member 142664114-Aug-13 9:24 
QuestionCool, Gave you a Five... Pin
ProtoBytes25-Mar-10 1:11
ProtoBytes25-Mar-10 1:11 
GeneralArray.Sort and Functional Quicksort Pin
Tuomas Hietanen2-Oct-08 3:28
Tuomas Hietanen2-Oct-08 3:28 
QuestionMemory usage? Pin
JasonDiplomat22-Sep-08 15:21
JasonDiplomat22-Sep-08 15:21 
GeneralYo here, it is.... Pin
Member 287207519-Sep-08 4:11
Member 287207519-Sep-08 4:11 
QuestionWhat about speed? Pin
s.illyuhin19-Sep-08 2:18
s.illyuhin19-Sep-08 2:18 
Generalref Pin
jpmik18-Sep-08 22:32
jpmik18-Sep-08 22:32 
GeneralRe: ref Pin
BillHines22-Sep-08 7:51
BillHines22-Sep-08 7:51 
GeneralRe: ref Pin
jpmik22-Sep-08 8:28
jpmik22-Sep-08 8:28 
GeneralRe: ref Pin
BillHines22-Sep-08 10:22
BillHines22-Sep-08 10:22 
Sorry, my bad, you are right here. Arrays are reference types and always resolve down to the address of first element of the array being passed. This is dangerous since you always act on the original array (possible modification of data you wish to keep in tact). The programmer should always copy the reference type data, modify it and return the copy, if he wishes to modify data without affecting the original. I was thinking of value types. Here is the correct way to modify both by value and by reference.

Sorry, its visual basic not c#, but you get the idea.

Module Module1

Private Function ModifyTheArrayByVal(ByVal aiArray() As Integer) As Integer()
Dim iLocalArray(aiArray.Length - 1I) As Integer
Array.Copy(aiArray, iLocalArray, aiArray.Length)
iLocalArray(0) = 1I
iLocalArray(1) = 2I
Return iLocalArray
End Function

Private Sub ModifyTheArrayByRef(ByVal aiArray() As Integer)
aiArray(0) = 1I
aiArray(1) = 2I
End Sub

Sub Main()
Dim iOriginalArray As Integer() = {0I, 0I}

Dim iNewArray() As Integer = ModifyTheArrayByVal(iOriginalArray)
Console.WriteLine("ByVal Original Array contains elements {0}, {1}", iOriginalArray(0), iOriginalArray(1))

Console.WriteLine("ByVal New Array contains elements {0}, {1}", iNewArray(0), iNewArray(1))
Console.WriteLine()


Console.WriteLine("ByRef Original Array contains elements {0}, {1}", iOriginalArray(0), iOriginalArray(1))
ModifyTheArrayByRef(iOriginalArray)
Console.WriteLine("ByRef New Array contains elements {0}, {1}", iOriginalArray(0), iOriginalArray(1))
Console.WriteLine()
Console.ReadLine()
End Sub

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.