QuickSortImplementation

QuickSortImplementation - //subrange and elements in R will...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Implementation -use the same array to store L and G using sub-ranges of the original array -no additional memory needed void quicksort(int *s, int n) { /************************************** Input: “s” unsorted array of ints “n” number of elements in array Output: “s” sorted array of ints ************************************* */ quicksortSubrange(s, 0, n-1); } void quicksortSubrange(int *2, int left, int right) { /**************************************** Input: “s” array where subrange is stored “left” index in “s” of first element “right” index in “s” of last element *************************************** */ if(left >= right) { return; } //use rightmost element as pivot int x = s[right]; //divide subrange in L, E, G int l=left; int r=right; //we shall swap elements in l and r such that the elements in L will be in the left side of
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: //subrange and elements in R will be on the right side of subrange while(l <= r) { //move l to the right unil we find an element that does not belong to L while(l < r && s[r] <x) { l++; //s[r]<=x handles cases where different indexes have equal value } //move r to the left until we find an element that doesn't belong to G while(l<r && s[r]>x) { r--; } //if l and r have not crossed eachother, then l and r are indexes of numbers that do not //belong to L or G. We swap them if(l < r) { int tmp = s[l]; s[l] = s[r]; s[r] = tmp; } } //while //now we have L and G. We need to position x in between L and G //swap x w/ the index in l int tmp = s[l]; s[l] = s[right]; s[right] = tmp; //now the pivot is in l. Recur. In L and G quicksortSubrange(s, left, l-1); quicksortSubrange(s+1, l+1/*(L+one)*/, right); } //end quicksortSubrange...
View Full Document

This note was uploaded on 02/04/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue.

Page1 / 2

QuickSortImplementation - //subrange and elements in R will...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online