zoukankan      html  css  js  c++  java
  • SDUT 3399 数据结构实验之排序二:交换排序

    数据结构实验之排序二:交换排序

    Time Limit: 1000MS Memory Limit: 65536KB

    Problem Description

    冒泡排序和快速排序都是基于"交换"进行的排序方法,你的任务是对题目给定的N个(长整型范围内的)整数从小到大排序,输出用冒泡和快排对这N个数排序分别需要进行的数据交换次数。

    Input

    连续多组输入数据,每组数据第一行给出正整数N(N ≤ 10^5),随后给出N个整数,数字间以空格分隔。

    Output

    输出数据占一行,代表冒泡排序和快速排序进行排序分别需要的交换次数,数字间以1个空格分隔,行末不得有多余空格。

    Example Input

    8
    49 38 65 97 76 13 27 49

    Example Output

    15 9

    Hint

    注意:数据相等时不做交换

    DQE:

    冒泡和快排,注意快排是怎么统计次数的,冒泡时下标从1和0开始时的循环条件的区别~

     1 #include <iostream>
     2 #include <cstdio>
     3 using namespace std;
     4 
     5 int buble(int *f,int n)
     6 {
     7     int i,j,count=0;;
     8     for(i=1;i<=n-1;i++)
     9         for(j=1;j<=n-i;j++)
    10             if(f[j]>f[j+1])
    11             {
    12                 count++;
    13                 int t=f[j];f[j]=f[j+1];f[j+1]=t;
    14             }
    15     return count;
    16 }
    17 
    18 int qs(int *f,int l,int r)
    19 {
    20     int count=0;
    21     if(l>=r)
    22         return 0;
    23     int i=l,j=r;
    24     int k=f[i];
    25     while(i<j)
    26     {
    27         while(i<j&&f[j]>=k)
    28             j--;
    29         f[i]=f[j];
    30         if(i!=j)
    31             count++;
    32         while(i<j&&f[i]<=k)
    33             i++;
    34         f[j]=f[i];
    35         if(i!=j)
    36             count++;
    37     }
    38     f[i]=k;
    39     return count+qs(f,l,i-1)+qs(f,i+1,r);
    40 }
    41 
    42 int main()
    43 {
    44     int n;
    45     while(scanf("%d",&n)!=EOF)
    46     {
    47         int f1[100010]={0},f2[100010]={0},i;
    48         for(i=1;i<=n;i++)
    49         {
    50             scanf("%d",f1+i);
    51             *(f2+i)=*(f1+i);
    52         }
    53         printf("%d %d
    ",buble(f1,n),qs(f2,1,n));
    54     }
    55     return 0;
    56 }
    57 
    58 /***************************************************
    59 User name: ***
    60 Result: Accepted
    61 Take time: 0ms
    62 Take Memory: 928KB
    63 Submit time: 2016-12-03 13:56:27
    64 ****************************************************/
  • 相关阅读:
    Leetcode.11 Container with Most Water
    Leetcode.19 Remove Nth Node From End of List
    Leetcode23. Merge K sorted List
    leetcode287. Find the duplicate Number
    LeetCode234. Palindrome Linked List
    leetcode.142 LinkedList Cycle II
    UINavigationController
    UITableView的性能优化1
    iOS触摸事件
    UITableView的性能优化
  • 原文地址:https://www.cnblogs.com/Leroscox/p/6128630.html
Copyright © 2011-2022 走看看