Всем привет. Выполняю домашнее задание (да, наверное глупо сюда постить, но всё же). Так вот, нужно написать быструю сортировку (quicksort) и прогнать через неё массив данных (текстовый файл с числами) и посчитать количество произведённых сравнений. Вся проблема в том, что, когда основой выбирается самый левый элемент, то всё считается хорошо, а
(
Read more... )
Comments 13
Reply
Reply
while (i < j); - не должно ли быть здесь <=?
Reply
Reply
Reply
public static void qsort(int[] aToSort, int left, int right)
{
numberOfComparisons += (right - left);
int i = left;
int j = right;
int m = aToSort[left];
do
{
while (aToSort[i] < m) ++i;
while (aToSort[j] > m) --j;
if (i <= j)
{
int temp = aToSort[i];
aToSort[i] = aToSort[j];
aToSort[j] = temp;
i++; j--;
}
} while (i <= j);
if (left < j) qsort(aToSort, left, j);
if (i
* This source code was highlighted with Source Code Highlighter.
Но не проходило количество сравнений.
Reply
Your recursive call begins with the pivot at the left end of the array segment you are partitioning. You go element-by element rightwards from the next one over. When you come across an element that's greater than the pivot, just go to the next one. When the element is less than the pivot, swap it with one nearer the beginning of the array. Keep doing this and when you get to the end, you have partitioned the array EXCEPT the pivot itself is still at the beginning. But you've been keeping track (with 'i' in Tim's slide) of the array position that separates "stuff less than the pivot" with "stuff greater than the pivot". So just swap the pivot with the rightmost array element that's less than it. Now you have "stuff less than the pivot" all together on the left and "stuff greater than the pivot" all together on the right - the inputs to your next set of recursive calls.
Reply
Reply
...
[2, 1]
First element as pivot : 1 comparisons.
Last element as pivot : 1 comparisons.
Median of 3 as pivot : 1 comparisons."
дык, вы хоть на результат сортировки этого кейса посмотрите.
Reply
Reply
http://www.youtube.com/watch?v=aMzgVshG6CI
Reply
Leave a comment