【问题标题】:Bubble sort with array size具有数组大小的冒泡排序
【发布时间】:2020-04-05 09:21:41
【问题描述】:

我想对 arraylist 的 n 个元素进行冒泡排序。我不想像下面那样首先声明数组列表,而是想使用 for 循环创建数组列表。 所以这是先声明arraylist的代码:

// A function to implement bubble sort  
void bubbleSort(int arr[], int n)  
{  
    int i, j;
    bool swapped; 
    int comparisons=0;
    for (i = 0; i < n-1; i++)  {
      swapped = false;
    // Last i elements are already in place  
    for (j = 0; j < n-i-1; j++)
    {
        comparisons++;
        if (arr[j] > arr[j+1])  
            {
                int temp = arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
                swapped = true; 
            }
    }
    if (swapped == false) 
        break; 
    }   
    cout << "Number of comparisons = " << comparisons << endl;
}  

/* Function to print an array */
void printArray(int arr[], int size)  
{  
    int i;  
    for (i = 0; i < size; i++)  
        cout << arr[i] << " ";  
    cout << endl;  
}  

// Driver code  
int main()  
{  
    int arr[] = {1, 2, 3, 4, 5};  
    int n = 5;  
    bubbleSort(arr, n);  
    cout<<"Sorted array: \n";  
    printArray(arr, n);  
}  

我不想这样做。

我做了这个,但我不知道为什么它不起作用。我对 C++ 还是很陌生。我可以知道是什么问题。非常感谢。

// A function to implement bubble sort  
void bubbleSort(int arr[], int n)  
{  
    int i, j;
    bool swapped; 
    int comparisons=0;
    for (i = 0; i < n-1; i++)  {
      swapped = false;
    // Last i elements are already in place  
    for (j = 0; j < n-i-1; j++)
    {
        comparisons++;
        if (arr[j] > arr[j+1])  
            {
                int temp = arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
                swapped = true; 
            }
    }
    if (swapped == false) 
        break; 
    }   
    cout << "Number of comparisons = " << comparisons << endl;
}  

/* Function to print an array */
void printArray(int arr[], int size)  
{  
    int i;  
    for (i = 0; i < size; i++)  
        cout << arr[i] << " ";  
    cout << endl;  
}  

【问题讨论】:

  • '我不知道为什么它不起作用'。它以什么方式不起作用?编译错误?运行时错误?运行,但行为错误?

标签: c++ arrays bubble-sort


【解决方案1】:

有两个问题:

  1. 数组索引为 0。
  2. 可变长度数组在 C++ 中是不合法的。

所以写main喜欢:

// Driver code  
int main()  
{  
    int n = 5;  
    int* arr = new int[n];
    for(int i=0; i<n; i++){
        arr[i]=i+1;
        cout<<arr[i];
        cout<<endl;
    }
    bubbleSort(arr, n);  
    cout<<"Sorted array: \n";  
    printArray(arr, n);
    delete[] arr;
}

【讨论】:

  • 谢谢!抱歉,如果我想创建数组列表的递减顺序怎么办?我试过 for(int i=n; i>=1; i--) 但似乎没有用
  • @fullsun 你可以使用for(int i=n-1; i&gt;=0; i--){ arr[i]=i+1; ... } 然后
猜你喜欢
  • 2016-02-10
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
  • 2016-02-27
  • 1970-01-01
相关资源
最近更新 更多