Home »
Ruby »
Ruby Programs
Ruby program to sort an array in ascending order using quick sort
Ruby Example: Write a program to sort an array in ascending order using quick sort.
Submitted by Nidhi, on January 21, 2022
Problem Solution:
In this program, we will create an array of integers and then we will sort the created array in ascending order using quicksort.
Program/Source Code:
The source code to sort an array in ascending order using quicksort is given below. The given program is compiled and executed successfully.
# Ruby program to sort an array in ascending order
# using Quick Sort
def QuickSort(arr, first, last)
pivot= 0;
temp = 0;
i = 0;
j = 0;
if(first < last)
pivot = first;
i = first;
j = last;
while(i<j)
while(arr[i]<=arr[pivot] && i<last)
i=i + 1;
end
while (arr[j] > arr[pivot])
j = j - 1;
end
if(i < j)
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
end
end
temp = arr[pivot];
arr[pivot] = arr[j];
arr[j] = temp;
QuickSort(arr, first, j - 1);
QuickSort(arr, j + 1, last);
end
end
arr = [12,39,49,87,68];
QuickSort(arr,0,4);
i=0;
print "Sorted Array: \n";
while(i<5)
print arr[i]," ";
i=i+1;
end
Output:
Sorted Array:
12 39 49 68 87
Explanation:
In the above program, we defined a method QuickSort() to sort an array in ascending order. And, we use recursion to use apply the quick sort process effectively. Using the QuickSort() method, we divide the given array into small sub-arrays. Then we sort sub-arrays recursively.
Ruby Arrays Programs »