在Shell Sort C ++中跟踪数组中元素的移动次数

时间:2016-12-23 07:27:44

标签: c++ arrays sorting shellsort

我正在进行有关在C ++中实现Shell Sort的这项任务。我已经设法获得Shell Sort中数组中元素之间的比较数。但是,我无法弄清楚在比较发生后如何识别元素的移动次数。这是我的Shell Sort代码(我从Internet获取此代码)

int shellSort(int arr[], int n) {
int compr = 0;      //indicate num of comparison
cout << endl << "Sorting using Shell Sort..." << endl << endl;
// Start with a big gap, then reduce the gap
for (int gap = n/2; gap > 0; gap /= 2) {
    compr++;        //the gap>0 comparison
    for (int i = gap; i < n; i += 1) {
        compr++;    // the i<size comparison
        // add a[i] to the elements that have been gap sorted
        // save a[i] in temp and make a hole at position i
        int temp = arr[i];
        // shift earlier gap-sorted elements up until the correct 
        // location for a[i] is found
        int j;            
        for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
            arr[j] = arr[j - gap];
            compr++;    // the j>=gap comparison
            compr++;    // the temp<arr[j-gap] comparison
        }            
        //  put temp (the original a[i]) in its correct location
        arr[j] = temp;
    }
}
cout << "Number of Comparison in Array of " << n << " Elements : " << compr << endl;}

希望有人可以帮我解决这个问题。提前谢谢。

1 个答案:

答案 0 :(得分:0)

检查下面的代码,其中新的变量移动表示在排序过程中元素的移动次数:

int shellSort(int arr[], int n) {
    int compr = 0;      //indicate num of comparison
    int moves = 0;
    cout << endl << "Sorting using Shell Sort..." << endl << endl;

    // Start with a big gap, then reduce the gap
    for (int gap = n/2; gap > 0; gap /= 2) {
        compr++;        //the gap>0 comparison

        for (int i = gap; i < n; i += 1) {
            compr++;    // the i<size comparison
            // add a[i] to the elements that have been gap sorted
            // save a[i] in temp and make a hole at position i
            int temp = arr[i];
            // shift earlier gap-sorted elements up until the correct
            // location for a[i] is found
            int j;

            for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
                arr[j] = arr[j - gap];
                compr++;    // the j>=gap comparison
                compr++;    // the temp<arr[j-gap] comparison
                moves+=2;     // elements are swapped / moved
            }

            //  put temp (the original a[i]) in its correct location
            arr[j] = temp;
        }
    }
    cout << "Number of Comparison in Array of " << n << " Elements : " << compr << endl;
    cout << "Number of Moves in Array of " << n << " Elements : " << moves << endl;
    return 0;
}

假设将两个元素交换到另一个位置是2次移动。