简体   繁体   English

具有数组大小的冒泡排序

[英]Bubble sort with array size

I want to do bubble sort for n elements of arraylist.我想对 arraylist 的 n 个元素进行冒泡排序。 Instead of declaring the arraylist first like below, I want to create the arraylist using for loops.我不想像下面那样首先声明 arraylist,而是想使用 for 循环创建 arraylist。 So this is the code of declaring the arraylist first:所以这是首先声明 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);  
}  

which I do not want to do.我不想这样做。

I have made this, but I do not know why it does not work.我做了这个,但我不知道为什么它不起作用。 I'm still quite new with C++.我对 C++ 还是很陌生。 May I know what's the problem.我可以知道是什么问题。 Thank you so much.太感谢了。

// 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;  
}  

There are two problems:有两个问题:

  1. Arrays are 0-indexed. Arrays 是 0 索引的。
  2. Variable length array which is not really legal in C++.在 C++ 中不合法的可变长度数组。

So write main like:所以写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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM