zoukankan      html  css  js  c++  java
  • PTA 冒泡排序

    6-4 冒泡排序 (10 分)
     

    编程实现冒泡排序函数。void bubbleSort(int arr[], int n);。其中arr存放待排序的数据,n为数组长度(1≤n≤1000)。

    函数接口定义如下:

    /* 对长度为n的数组arr执行冒泡排序 */
    void bubbleSort(int arr[], int n);
    

    请实现bubbleSort函数,使排序后的数据从小到大排列。

    裁判测试程序样例:

    #include <stdio.h>
    
    #define N 1000
    int arr[N];
    
    /* 对长度为n的数组arr执行冒泡排序 */
    void bubbleSort(int arr[], int n);
    
    /* 打印长度为n的数组arr */
    void printArray(int arr[], int n);
    
    void swap(int *xp, int *yp) {
        int temp = *xp;
        *xp = *yp;
        *yp = temp;
    }
    
    int main() {
        int n, i;
        scanf("%d", &n);
        for (i = 0; i < n; ++i) {
            scanf("%d", &arr[i]);
        }
        bubbleSort(arr, n);
        printArray(arr, n);
        return 0;
    }
    /* 打印长度为n的数组arr */
    void printArray(int arr[], int n) {
        int i;
        for (i = 0; i < n; i++) {
            printf("%d", arr[i]);
            if (i < n - 1)    /* 下标0..n-2每个元素后面有个空格 */
                printf(" ");   /*下标n-1,也就是最后一个元素后面没有空格*/
        }
        printf("
    ");  /* 一行打印完后换行 */
    }
    
    /* 你的代码将嵌在这里 */
    

    输入样例:

    10
    1 19 9 11 4 3 5 8 10 6
    

    输出样例:

    1 3 4 5 6 8 9 10 11 19

     1 void bubbleSort(int arr[], int n){
     2     int m=n-1,flag=1;
     3     while(m>0&&flag==1){
     4         flag=0;
     5         for(int j=0;j<m;j++){
     6             if(arr[j]>arr[j+1]){
     7                 flag=1;
     8                 int t=arr[j];
     9                 arr[j]=arr[j+1];
    10                 arr[j+1]=t;
    11             }
    12         }
    13         --m;
    14     }    
    15 }

    方法2

     1 void bubbleSort(int arr[], int n){
     2     int i=n-1;
     3     while(i){
     4         int k=0;
     5         for(int j=0;j<i;j++){
     6             if(arr[j+1]<arr[j]){
     7                 int t=arr[j];
     8                 arr[j]=arr[j+1];
     9                 arr[j+1]=t;
    10                 k=j;
    11             }
    12         }
    13         i=k;
    14     }
    15 }
     
  • 相关阅读:
    Analysis Services features supported by SQL Server editions
    Azure DevOps to Azure AppServices
    Power BI For Competition
    Win10开机“提示语音”以及”随机播放音乐”
    Azure DevOps
    Allow Only Ajax Requests For An Action In ASP.NET Core
    Mobile CI/CD 101
    Configure SSL for SharePoint 2013
    AWS Step Function Serverless Applications
    Cordova Upload Images using File Transfer Plugin and .Net core WebAPI
  • 原文地址:https://www.cnblogs.com/DirWang/p/11929692.html
Copyright © 2011-2022 走看看