Skip to content

Commit 5620932

Browse files
committed
Replace partition1 with a more reliable variant
1 parent 50f6ed9 commit 5620932

1 file changed

Lines changed: 20 additions & 18 deletions

File tree

archive/c/c-plus-plus/quick-sort.cpp

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -65,28 +65,30 @@ vector<int> convert(string s)
6565

6666
int partition1(vector<int> &a, int l, int u)
6767
{
68-
int v, i, j, temp;
69-
v = a[l];
70-
i = l;
71-
j = u + 1;
72-
do
68+
int pivot = a[l];
69+
int i = l;
70+
int j = u + 1;
71+
72+
while (true)
7373
{
7474
do
75-
i++;
76-
while (a[i] < v && i <= u);
75+
{
76+
++i;
77+
} while (i <= u && a[i] < pivot);
78+
7779
do
78-
j--;
79-
while (v < a[j]);
80-
if (i < j)
8180
{
82-
temp = a[i];
83-
a[i] = a[j];
84-
a[j] = temp;
85-
}
86-
} while (i < j);
87-
a[l] = a[j];
88-
a[j] = v;
89-
return (j);
81+
--j;
82+
} while (a[j] > pivot);
83+
84+
if (i >= j)
85+
break;
86+
87+
swap(a[i], a[j]);
88+
}
89+
90+
swap(a[l], a[j]);
91+
return j;
9092
}
9193

9294
void quick_sort(vector<int> &a, int l, int u)

0 commit comments

Comments
 (0)