Movatterモバイル変換


[0]ホーム

URL:


Open In App

Quicksort is one of the most efficient sorting algorithms and is commonly implemented using recursion. However, recursion can cause stack overflow errors when dealing with very large datasets. To overcome this, we can use an iterative version of Quicksort that replaces recursive calls with an explicit stack to manage subarrays.

How It Works

Python Code Implementation

1. Partition Function:This function places the pivot element at its correct sorted position.

Python
defpartition(arr,l,h):i=l-1pivot=arr[h]forjinrange(l,h):ifarr[j]<=pivot:i+=1arr[i],arr[j]=arr[j],arr[i]arr[i+1],arr[h]=arr[h],arr[i+1]returni+1

2. Iterative QuickSort Function: This function uses a stack instead of recursion.

Python
defquickSortIterative(arr,l,h):size=h-l+1stack=[0]*sizetop=-1top+=1stack[top]=ltop+=1stack[top]=hwhiletop>=0:h=stack[top]top-=1l=stack[top]top-=1p=partition(arr,l,h)ifp-1>l:top+=1stack[top]=ltop+=1stack[top]=p-1ifp+1<h:top+=1stack[top]=p+1top+=1stack[top]=h

3. Driver Code

Python
arr=[4,3,5,2,1,3,2,3]n=len(arr)quickSortIterative(arr,0,n-1)print("Sorted array is:")foriinrange(n):print(arr[i],end=" ")

Output:

Sorted array is:
1 2 2 3 3 3 4 5

Complete Code:

Python
defpartition(arr,l,h):i=l-1pivot=arr[h]forjinrange(l,h):ifarr[j]<=pivot:i+=1arr[i],arr[j]=arr[j],arr[i]arr[i+1],arr[h]=arr[h],arr[i+1]returni+1defquickSortIterative(arr,l,h):size=h-l+1stack=[0]*sizetop=-1top+=1stack[top]=ltop+=1stack[top]=hwhiletop>=0:h=stack[top]top-=1l=stack[top]top-=1p=partition(arr,l,h)ifp-1>l:top+=1stack[top]=ltop+=1stack[top]=p-1ifp+1<h:top+=1stack[top]=p+1top+=1stack[top]=harr=[4,3,5,2,1,3,2,3]n=len(arr)quickSortIterative(arr,0,n-1)print("Sorted array is:")foriinrange(n):print(arr[i],end=" ")

Output
Sorted array is:1 2 2 3 3 3 4 5

Explanation:

  • partition():selects the last element as pivot and places it at its correct position while rearranging other elements around it.
  • quickSortIterative():manages the sorting process using a stack to store subarray ranges that need sorting.
  • The loop continues until the stack is empty, meaning all subarrays are sorted.

Related Articles:


Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp