美文网首页
Chapter6——基础算法——排序

Chapter6——基础算法——排序

作者: crishawy | 来源:发表于2019-08-02 17:02 被阅读0次

1. 题目列表

  • POJ2388(排序,水题)
  • POJ2299(求逆序对,归并排序、树状数组、线段树)

2. POJ2299——Ultra-QuickSort

2.1 题目描述

Description

image

In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence

<center>9 1 0 5 4 ,</center>

Ultra-QuickSort produces the output

<center>0 1 4 5 9 .</center>

Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.

Input

The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.

Output

For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.

Sample Input
5
9
1
0
5
4
3
1
2
3
0

Sample Output

6
0

2.2 解决思路

数组的长度达到500,000,使用冒泡排序记录交换次数明显超时。

这里参考三种解法:

a. 归并排序
归并排序的思路:

    给出一个无序数组,要求求出冒泡排序的交换次数,
    时间复杂度为O(n^{2})的原始冒泡排序会超时。
     
    该题目的本质是求数组的逆序对个数,
    如在9 1 0 5 4数组中,逆序对(9,1),(9,0),(9,5),(9,4),(1,0),(5,4)共6个,
    所以共需交换6次。
     
    解法1:归并排序。
        对于原始数组:2 3 5 9 1 4 6 8
        两两分组在某一次归并过程中:
        a1: 2 3 5 9
        a2: 1 4 6 8
        由于a2一定在a1的后面,所以在分别比较a1和a2的数的顺序时,如果出现逆序,
        则记录结果为:ans += l2 - i。如比较2和1时,由于2>1,所以为逆序,此时冒泡交换的次数
  为a1中2后面的个数(包括2本身) 

b. 线段树

c. 树状数组

相关文章

  • Chapter6——基础算法——排序

    1. 题目列表 POJ2388(排序,水题) POJ2299(求逆序对,归并排序、树状数组、线段树) 2. PO...

  • 开发者应该掌握的几种排序算法

    该篇文章主要介绍了算法基础以及几种常见的排序算法:选择排序、插入排序、冒泡排序、快速排序、堆排序。 一、算法基础 ...

  • 算法-排序算法总结

    排序类型总结 1 排序算法基础实现 2 排序算法应用 2.1 基础排序 2.2 计数排序应用 2.3 快排应用 2...

  • 算法与数据结构(二):排序篇-O(n^2)算法:选择 &

    排序基础 O(n^2)的算法虽然简单,但也实用!让我们从最简单的基础排序算法开始,打开我们的算法大门! 排序算法 ...

  • 基础排序算法总结

    排序算法分为内部排序和外部排序,而我们经常说的基础排序算法,都是内部排序算法。包括冒泡排序,选择排序,插入排序,快...

  • 排序算法

    概述 一般排序算法(以元素比较为基础) => 快速排序、归并排序、插入排序、冒泡排序、堆排序 特殊排序算法 => ...

  • 算法汇总

    关于算法: 基础技巧:分治、二分、贪心排序算法:快速排序、归并排序、计数排序搜索算法:回溯、递归、深度优先遍历,广...

  • 插入排序算法实现

    排序算法是最常见,最基础的算法,作者文集中记录了两种排序算法(插入排序,归并排序) 插入排序算法实现很简单直接,附...

  • 排序算法总结

    基础排序算法 基础排序算法相关接口和实现类 接口: 实现类(后续排序的父类): 1.选择排序 两层循环:内层循环进...

  • 算法与数据结构简介

    0x01 算法 基础技巧:分治、二分、贪心 排序算法:快速排序、归并排序、计数排序 搜索算法:回溯、递归、深度优先...

网友评论

      本文标题:Chapter6——基础算法——排序

      本文链接:https://www.haomeiwen.com/subject/ybldrctx.html