From 796c32aa4606977a72c20358766ca895a88bd746 Mon Sep 17 00:00:00 2001 From: MiracleShadow Date: Fri, 5 Aug 2022 10:36:21 +0800 Subject: [PATCH 1/2] fix quick_sort.cpp bug Fix index access overflow --- sorting/quick_sort.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index ff66b4cf20e..0e3d5805abc 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -93,7 +93,7 @@ int main() { std::cout << "\n"; std::cin >> arr[i]; } - quickSort(arr, 0, size); + quickSort(arr, 0, size - 1); std::cout << "Sorted array\n"; show(arr, size); delete[] arr; From f0f1584432512ab675f283a0d1c85f825bb0e241 Mon Sep 17 00:00:00 2001 From: MiracleShadow <1210768621@qq.com> Date: Sun, 14 Aug 2022 23:34:35 +0800 Subject: [PATCH 2/2] :label: fix C-style arrays --- sorting/quick_sort.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/sorting/quick_sort.cpp b/sorting/quick_sort.cpp index 0e3d5805abc..c488c925949 100644 --- a/sorting/quick_sort.cpp +++ b/sorting/quick_sort.cpp @@ -23,6 +23,7 @@ #include #include +#include namespace sorting { /** @@ -34,7 +35,7 @@ namespace sorting { * */ -int partition(int arr[], int low, int high) { +int partition(std::vector &arr, int low, int high) { int pivot = arr[high]; // taking the last element as pivot int i = (low - 1); // Index of smaller element @@ -60,7 +61,7 @@ int partition(int arr[], int low, int high) { * low --> Starting index, * high --> Ending index */ -void quickSort(int arr[], int low, int high) { +void quickSort(std::vector &arr, int low, int high) { if (low < high) { int p = partition(arr, low, high); quickSort(arr, low, p - 1); @@ -73,19 +74,19 @@ void quickSort(int arr[], int low, int high) { using sorting::quickSort; // prints the array after sorting -void show(int arr[], int size) { +void show(const std::vector &arr, int size) { for (int i = 0; i < size; i++) std::cout << arr[i] << " "; std::cout << "\n"; } /** Driver program to test above functions */ int main() { - int size; + int size = 0; std::cout << "\nEnter the number of elements : "; std::cin >> size; - int *arr = new int[size]; + std::vector arr(size); std::cout << "\nEnter the unsorted elements : "; @@ -96,6 +97,5 @@ int main() { quickSort(arr, 0, size - 1); std::cout << "Sorted array\n"; show(arr, size); - delete[] arr; return 0; }