Free Essay

Quick Sort Analysis

In:

Submitted By RohithRoshanDevu
Words 1014
Pages 5
Here is an analysis of the time complexity of quick-sort in detail. In quick sort, we pick an element called the pivot in each step and re-arrange the array in such a way that all elements less than the pivot now appear to the left of the pivot, and all elements larger than the pivot appear on the right side of the pivot. In all subsequent iterations of the sorting algorithm, the position of this pivot will remain unchanged, because it has been put in its correct place. The total time taken to re-arrange the array as just described, is always O(n)1 , or αn where α is some constant [see footnote]. Let us suppose that the pivot we just chose has divided the array into two parts - one of size k and the other of size n − k. Notice that both these parts still need to be sorted. This gives us the following relation: T (n) = T (k) + T (n − k) + αn where T (n) refers to the time taken by the algorithm to sort n elements. WORST CASE ANALYSIS: Now consider the case, when the pivot happened to be the least element of the array, so that we had k = 1 and n − k = n − 1. In such a case, we have: T (n) = T (1) + T (n − 1) + αn Now let us analyse the time complexity of quick sort in such a case in detail by solving the recurrence as follows: T (n) = T (n − 1) + T (1) + αn = [T (n − 2) + T (1) + α(n − 1)] + T (1) + αn (Note: I have written T (n − 1) = T (1) + T (n − 2) + α(n − 1) by just substituting n − 1 instead of n. Note the implicit assumption that the pivot that was chosen divided the original subarray of size n − 1 into two parts: one of size n − 2 and the other of size 1.) = T (n − 2) + 2T (1) + α(n − 1 + n) (by simplifying and grouping terms together) = [T (n − 3) + T (1) + α(n − 2)] + 2T (1) + α(n − 1 + n) = T (n − 3) + 3T (1) + α(n − 2 + n − 1 + n) = [T (n − 4) + T (1) + α(n − 3)] + 3T (1) + α(n − 2 + n − 1 + n)
Here is how we can perform the partitioning: (1) Traverse the original array once and copy all the elements less than the pivot into a temporary array, (2) Copy the pivot into the temporary array, (3) Copy all elements greater than the pivot into the temporary array, and (4) Transfer the contents of the temporary array into the original array, thus overwriting the original array. This takes a total of 4n operations. There do exist ways to perform such a partitioning in-place, i.e. without creating a temporary array, as well. These techniques do speed up quicksort by a constant factor, but they are not important for understanding the overall quicksort algorithm.
1

1

= T (n − 4) + 4T (1) + α(n − 3 + n − 2 + n − 1 + n) = T (n − i) + iT (1) + α(n − i + 1 + ..... + n − 2 + n − 1 + n) (Continuing likewise till the ith step.) = T (n − i) + iT (1) + α( i−1 j=0 (n

− j)) (Look carefully at how the summation is being written.)

Now clearly such a recurrence can only go on until i = n − 1 (Why? because otherwise n − i would be less than 1). So, substitute i = n − 1 in the above equation, which gives us: T (n) = T (1) + (n − 1)T (1) + α n−2 j=0 (n

− j) n−2 j=0 j

= nT (1) + α(n(n − 2) − (n − 2)(n − 1)/2) (Notice that by a formula we earlier derived in class) which is O(n2 ).

=

n−2 j=1 j

= (n − 2)(n − 1)/2

This is the worst case of quick-sort, which happens when the pivot we picked turns out to be the least element of the array to be sorted, in every step (i.e. in every recursive call). A similar situation will also occur if the pivot happens to be the largest element of the array to be sorted. BEST CASE ANALYSIS: The best case of quicksort occurs when the pivot we pick happens to divide the array into two exactly equal parts, in every step. Thus we have k = n/2 and n − k = n/2 for the original array of size n. Consider, therefore, the recurrence: T (n) = 2T (n/2) + αn = 2(2T (n/4) + αn/2) + αn (Note: I have written T (n/2) = 2T (n/4) + αn/2 by just substituting n/2 for n in the equation T (n) = 2T (n/2) + αn.) = 22 T (n/4) + 2αn (By simplifying and grouping terms together). = 22 (2T (n/8) + αn/4) + 2αn = 23 T (n/8) + 3αn = 2k T (n/2k ) + kαn (Continuing likewise till the k th step) Notice that this recurrence will continue only until n = 2k (otherwise we have n/2k < 1), i.e. until k = log n. Thus, by putting k = log n, we have the following equation:

2

T (n) = nT (1) + αn log n, which is O(n log n). This is the best case for quicksort. It also turns out that in the average case (over all possible pivot configurations), quicksort has a time complexity of O(n log n), the proof of which is beyond the scope of our class. AVOIDING THE WORST CASE Practical implementations of quicksort often pick a pivot randomly each time. This greatly reduces the chance that the worst-case ever occurs. This method is seen to work excellently in practice. The other technique, which determinstically prevents the worst case from ever occurring, is to find the median of the array to be sorted each time, and use that as the pivot. The median can (surprisingly!) be found in linear time (the details of which are, again, beyond the scope of our course) but that is saddled with a huge constant factor overhead, rendering it suboptimal for practical implementations.

3

Similar Documents

Premium Essay

Comparative Analysis Of Sorting Algorithm

...COMPARATIVE ANALYSIS OF VARIOUS SORTING ALGORITHM ABSTRACT: Sorting is a commonly used operation in computer science. In addition to its main job, sorting is often required to facilitate some other operation such as searching, merging and normalization. A sorting algorithm consists of comparison, swap, and assignment operations. There are several elementary and advanced sorting algorithms that are being used in practical life as well as in computation such as Quick sort, Bubble sort, Merge sort, Bucket sort, Heap sort, Radix sort etc. But the application of these algorithms depends on the problem statement. This paper introduces MQ sort which combines the advantages of quick sort and Merge sort. The comparative analysis of performance and complexity...

Words: 2578 - Pages: 11

Premium Essay

Sort

...Computer Simulation Clump Sort: A Stable Alternative To Heap Sort For Sorting Medical Data Visvasuresh Victor Govindaswamy Matthew Caudill Jeff Wilson Computer Science Texas A&M University-Texarkana Texarkana, USA lovebat814@yahoo.com Computer Science Texas A&M University-Texarkana Texarkana, USA Computer Science Texas A&M University-Texarkana Texarkana, USA Daniel Brower G. Balasekaran, FACSM Computer Science Texas A&M University-Texarkana Texarkana, USA Medical and Sports Science Nanyang Technology University Singapore Abstract—Sorting data sets are a thoroughly researched field. Several sorting algorithms have been introduced and these include Bubble, Insertion, Selection, Shell, Quick, Merge and Heap. In this paper, we present a novel sorting algorithm, named Clump Sort, to take advantage of ordered segments already present in medical data sets. It succeeds in sorting the medical data considerably better than all the sorts except when using totally non-clumped data. In this test using totally nonclumped data, Heap sort does only slightly better than Clump sort. However, Clump sort has the advantage of being a stable sort as the original order of equal elements is preserved whereas in Heap sort, it is not since it does not guarantee that equal elements will appear in their original order after sorting. As such, Clump Sort will have considerably better data cache performance with both clumped and non-clumped data, outperforming Heap Sort on a modern desktop PC, because...

Words: 1753 - Pages: 8

Premium Essay

Clump Sort

...Computer Simulation Clump Sort: A Stable Alternative To Heap Sort For Sorting Medical Data Visvasuresh Victor Govindaswamy Computer Science Texas A&M University-Texarkana Texarkana, USA lovebat814@yahoo.com Matthew Caudill Computer Science Texas A&M University-Texarkana Texarkana, USA Jeff Wilson Computer Science Texas A&M University-Texarkana Texarkana, USA Daniel Brower Computer Science Texas A&M University-Texarkana Texarkana, USA G. Balasekaran, FACSM Medical and Sports Science Nanyang Technology University Singapore Abstract—Sorting data sets are a thoroughly researched field. Several sorting algorithms have been introduced and these include Bubble, Insertion, Selection, Shell, Quick, Merge and Heap. In this paper, we present a novel sorting algorithm, named Clump Sort, to take advantage of ordered segments already present in medical data sets. It succeeds in sorting the medical data considerably better than all the sorts except when using totally non-clumped data. In this test using totally nonclumped data, Heap sort does only slightly better than Clump sort. However, Clump sort has the advantage of being a stable sort as the original order of equal elements is preserved whereas in Heap sort, it is not since it does not guarantee that equal elements will appear in their original order after sorting. As such, Clump Sort will have considerably better data cache performance with both clumped and non-clumped data, outperforming Heap Sort on a modern desktop PC...

Words: 1753 - Pages: 8

Premium Essay

Gatau

...getting started getting started Copyright © 2006 ACL Services Ltd. All rights reserved. No part of these materials may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means (photocopying, electronic, mechanical, recording, or otherwise), without permission in writing from the publisher, except by a reviewer who may quote brief passages in a review. ACL 9 August 2006 ACL Services Ltd. 1550 Alberni Street Vancouver, BC Canada V6G 1A5 Telephone: +1-604-669-4225 E-mail: info@acl.com Web: www.acl.com Printed in Canada ACL, the ACL logo, the ACL logo with the text, "ACL Data you can trust. Results you can see." and Audit Command Language are trademarks or registered trademarks of ACL Services Ltd. Microsoft, Windows and Windows Server are trademarks or registered trademarks of Microsoft Corporation. AIX, OS/390, OS/400 and z/OS are registered trademarks of IBM Corporation. Linux is a registered trademark of Linus Torvalds. SAP, R/2 and R/3 are trademarks or registered trademarks of SAP AG. Crystal Reports is a trademark or registered trademark of Business Objects SA. All other trademarks are the property of their respective owners. 200607031748 C ONTENTS Chapter 1: Take your first look at ACL . . . . . . . . . . . . . . . . . . . . . 1 Making effective business decisions ................................................ 2 What can I use ACL for? ............................................................

Words: 14019 - Pages: 57

Premium Essay

Bald Guy

...is random, unprocessed facts that have a little or no value until they have undergone some sort of processing activity. Data processing information What is information? * Information is a set of meaningful data that is of use to somebody. * It is data that is associated with a specific meaning. * Information is transmitted every second of every day, and it is the infrastructure to every organisation. * If we could not transmit information, nothing in the world would be achieved. How do we know… * What people or systems want? * How they want it delivered? * How much they want? * How they want to pay for it? How is information expressed? * Visually? Hand gestures, body language, images, sign language * Verbally? Speech * Physically? Videos, writing What sort of quantitative data might your business collect? What do you like about our business? – questions Staff reviews Customer complaints What sort of quantitative data might your business collect? What do you like about our business? – questions Staff reviews Customer complaints What sort of qualitative data might your business collect? Income per year. See what products are selling quickly and ensure you buy more in for next time. See how much profit you are getting on different products Staff numbers Staff pay What sort of qualitative data might your business collect? Income per year. See what products are...

Words: 992 - Pages: 4

Free Essay

Sorting Algorithms

...performance of sorting algorithms. Like all complicated problems, there are many solutions that can achieve the same results. One sort algorithm can do sorting of data faster than another. A lot of sorting algorithms has been developed to enhance the performance in terms of computational complexity, memory and other factors. This paper choose two of the sorting algorithms among them selection sort and shell sort and compares the various performance factor among them. 1. INTRODUCTION Sorting is the rearrangement of things in a list into their correct lexicographic order. A number of sorting algorithms have been developed like include heap sort , merge sort, quick sort, selection sort all of which are comparison based sort .There is another class of sorting algorithms which are non comparison based sort. This paper gives the brief introduction about sorting algorithms [2] where it discuss about the class of sorting algorithms and their running times. It mainly analyses the performance between two sorting algorithms .Selection sort [3] and Shell sort [5]. Selection sort is the simple sorting method with a very simple sorting algorithm [3]. However the running time of this algorithm is not that optimal as compared to performance of best sorting algorithm .The analysis of the running time [4] concludes this thing. Shell sort is another comparison based sorting algorithm which is...

Words: 841 - Pages: 4

Free Essay

Sorting

...1. Use class Sort.java provided in class, the dual-pivot Quicksort of Java 8 (Arrays.sort), and RadixSort.java provided in class.  2. Do the following for Mergesort, Quicksort, Heapsort and dual-pivot Quicksort: a. Create 100,000 random keys (of type long) and sort them. Repeat this 100 times. b. Compute the average CPU time taken to sort the keys for the four methods. c. Comment on the results and compare them to the average-case complexities discussed in class.  As we discussed in the class, all these sorting algorithms I used for testing have the same average-case complexities with O (n log n). But the data I got which shows in the upper diagram illustrate that Quick sort is the most fast sorting method especially when you need to sort a large amount of data. Dual-pivot quicksort is also fast than merge sort and Heap sort. Heap sort can be used when the pending data between 1000-1000, 000, and for Merge sort is the first choice when there are more than 1M data. 3. Do the following for the four sorting methods of #2, and for Radix sort: a. Create 100,000 random strings of length 4 and sort them using the five sorting methods. b. Repeat (a) 10 times Compute the average CPU time taken to sort the keys for the five methods. c. Repeat (a) and (b) with strings of length 6, 8, 10. d. Create a table with the results and compare the times with the average-case and worstcase complexities as studied in class.  The length of string is 4: The length of string...

Words: 910 - Pages: 4

Premium Essay

Accounting

...Running Head: Financial Analysis Financial Analysis of Walt Disney Company Brittany ACC205 Professor 17 June 2013 Throughout this paper you as my reader are going to learn about my company, what they are all about including any type of competition they may be facing. You are also going to view the financial analysis of Walt Disney Co. which will include a horizontal analysis from three consecutive years, along with a ratio analysis which will be going over the current ratio, quick ratio and the cash to current liabilities ratio from a two year-period. First off let’s discuss what a horizontal analysis is before examining the analysis of Walt Disney Co. According to our text, “a horizontal analysis can be used to compare data from within two or more periods, side by side. In other words, it is intended to show the change in certain accounts from two separate accounting periods”(Walther, 2012). A horizontal analysis is good for investors, so they can look at the companies financial standing and see how they are doing when it comes to their income, and whether or not they are worth investing into as a company. This sort of analysis is very vital when it comes to investors, it should not be the answer to their decision on whether or not they should invest in a company, but it should give them some insight as to who well a company is doing financially. When it comes to Walt Disney Co, we are going to get some background information...

Words: 3796 - Pages: 16

Free Essay

Final Essay

...Twitter: social communication in the Twitter Age –Dhiraj Murthy 2013 Book Review Twitter has become one of the most popular social network over the years and it is such a bizarre that everyone is in depth of accessing the twitter and how its been used . It is such an important distinction to Facebook and other emergent social technologies . It allows people to use 140 character to send messages from their mobile internet devices . I found myself questioning about the first chapter of the book, is it worth the 140 character? The answers will continue on as you read this book . In the first few chapter of Murthy’s book, he explicates more about what is twitter, how it contextualize and also theorizing twitter. He stated a lot of ponderous information and example of the superintendence twitter with people. There is a few debate about the barriers between public and private that seems to blurred us. Interactive multicasting that blurs us on twitter might make us question on the consumers will definitely make an interesting story. This book is profound in its calibration and scope, yet Murthy is deliberating on todays provision of twitter. He highlights a lot of important issues such as privacy and the global village. Chapter four that explains about twitter and journalism makes me immersed in deep analytics through the end user who is required to capture and understand the real time flow of worldwide consciousness . Besides, twitter is an ambient news environment and...

Words: 888 - Pages: 4

Free Essay

The Data Structure

...以列为主的顺序分配 column major order 三角矩阵 truangular matrix 对称矩阵 symmetric matrix 稀疏矩阵 sparse matrix 转置矩阵 transposed matrix 链表 linked list 线性链表 linear linked list 单链表 single linked list 多重链表 multilinked list 循环链表 circular linked list 双向链表 doubly linked list 十字链表 orthogonal list 广义表 generalized list 链 link 指针域 pointer field 链域 link field 头结点 head node 头指针 head pointer 尾指针 tail pointer 串 string 空白(空格)串 blank string 空串(零串) null string 子串 substring 树 tree 子树 subtree 森林 forest 根 root 叶子 leaf 结点 node 深度 depth 层次 level 双亲 parents 孩子 children 兄弟 brother 祖先 ancestor 子孙 descentdant 二叉树 binary tree 平衡二叉树 banlanced binary tree 满二叉树 full binary tree 完全二叉树 complete binary tree 遍历二叉树 traversing binary tree 二叉排序树 binary sort tree 二叉查找树 binary search tree 线索二叉树 threaded binary tree 哈夫曼树 Huffman tree 有序数 ordered tree 无序数 unordered tree 判定树 decision tree 双链树 doubly linked tree 数字查找树 digital search tree 树的遍历 traversal of tree 先序遍历 preorder traversal 中序遍历...

Words: 1522 - Pages: 7

Premium Essay

The Silence Of The Lambs Trailer Analysis

...codes and conventions throughout the trailer and the quick establishment of the main character Starling who is a police officer. The use of a voice over allows the audience to know what is occurring and what the protagonist will have to face. The voice over explains severely murder have been occurring, the introduction of Starling allows he audience to have hope that she will be able to solve the murders. Starling is presented as being brave, telling the audience she “does not scare easily”. “At first the trailer begins with a non diegetic sound of a low tone soundtrack that eventually turns into a metal music with screams, this indicates to the audience that the rest of the trailer will be a dark heavy tale. The...

Words: 1044 - Pages: 5

Premium Essay

Case Study

...out material to be printed joining together with little mom-and-pop associations doing the same sort of work under huge distributors. Experiencing the book the Problems that we came to know are such tremendous issue that they are confronting and these could be seen in different trades additionally. To begin with key issue was the Engineering and Technology. So far we analyzed that the Competition was additionally a climbing issue that is bringing the organization down and getting things messed. Quality and Cost was turned into issues that came after the competitors enter the trade. Some small scale problems we examined were Lack of self interest in employees and Incentives and Benefits. Causes: * Engineering and Technology: As the technologies were developing step by step, helped the trade to expand the organizations, for example, Internet that helped a considerable measure to addition benefits and make work simple. As we read in the book the development of internet made outsources simpler for the bigger distributor in the business maintaining good quality. Initially the expense for the realistic transfer machine for remote typesetting was about $45,000 and the fast data line cost $10,000 a year. After the invention of digital computerized typesetting projects and the development of PCs and the internet helped to dropped the expense to $200 for typesetting and $1800 a quick data line. The ease completely pulled in the distributors of the business to have the new...

Words: 1532 - Pages: 7

Premium Essay

It- 3rd Year

...E-COMMERCE (TIT-501) UNIT I Introduction What is E-Commerce, Forces behind E-Commerce Industry Framework, Brief history of ECommerce, Inter Organizational E-Commerce Intra Organizational E-Commerce, and Consumer to Business Electronic Commerce, Architectural framework Network Infrastructure for E-Commerce Network Infrastructure for E-Commerce, Market forces behind I Way, Component of I way Access Equipment, Global Information Distribution Network, Broad band Telecommunication. UNIT-II Mobile Commerce Introduction to Mobile Commerce, Mobile Computing Application, Wireless Application Protocols, WAP Technology, Mobile Information Devices, Web Security Introduction to Web security, Firewalls & Transaction Security, Client Server Network, Emerging Client Server Security Threats, firewalls & Network Security. UNIT-III Encryption World Wide Web & Security, Encryption, Transaction security, Secret Key Encryption, Public Key Encryption, Virtual Private Network (VPM), Implementation Management Issues. UNIT - IV Electronic Payments Overview of Electronics payments, Digital Token based Electronics payment System, Smart Cards, Credit Card I Debit Card based EPS, Emerging financial Instruments, Home Banking, Online Banking. UNIT-V Net Commerce EDA, EDI Application in Business, Legal requirement in E -Commerce, Introduction to supply Chain Management, CRM, issues in Customer Relationship Management. References: 1. Greenstein and Feinman, “E-Commerce”, TMH 2. Ravi Kalakota, Andrew Whinston...

Words: 2913 - Pages: 12

Free Essay

Systems

...Component 01 - Computing Principles | AS-Level (H046) | A-Level (H446) | 1 The characteristics of contemporary processors, input, output and storage devices | Structure and function of the processor | The Arithmetic and Logic Unit (ALU), Control Unit and registers: Program Counter (PC), Accumulator (ACC), Memory Address Register (MAR), Memory Data Register (MDR), Current Instruction Register (CIR).Buses: data, address and control: How this relates to assembly language programs.The fetch-decode-execute cycle, including its effect on registers.The factors affecting the performance of the CPU, clock speed, number of cores, cache.Von Neumann, Harvard and contemporary processor architecture. | The use of pipelining in a processor to improve efficiency. | Types of processor | The differences between, and uses of, CISC and RISC processors.Multicore and parallel systems. | GPUs and their uses (including those not related to graphics). | Input, output and storage | How different input output and storage devices can be applied as a solution of different problems.The uses of magnetic, flash and optical storage devices.RAM and ROM.Virtual storage. | | 2 Software and software development | Operating systems | The need for, function and purpose of operating systems.Memory management (paging, segmentation and virtual memory).Interrupts, the role of interrupts and Interrupt Service Routines (ISR), role within the fetch decode execute cycle.Scheduling: round robin, first come...

Words: 1302 - Pages: 6

Free Essay

Marketing

...!1 | P a g e Semester 2, 2015 MKT10007 Fundamentals of Marketing Assignment 3: Guide to accompany Marketing Strategy PART 1 - Template Section 1: The marketplace and influencing factors What industry are we in? Before any analysis, some sort of scope should be provided at the beginning of any business report. A tree diagram is useful because:➢ A tree-diagram defines the scope and product-category structure of the “industry” of concern. ➢ Depicts aspects of an industry that are close together ➢ Showing which parts belong together ➢ Displaying both broad and narrow options ➢ Identifying the scope for the current report. The following could be used by a company such as Coca-Cola:Beverages Alcoholic Non-Alcoholic Hot Juice Milks ! Colas Cold Softdrink Energy Lemonade Water Other Flavours This diagram shows that the “industry” could be defined as: • Beverages (the broadest definition) • Non-Alcoholic beverages • Cold non-alcoholic beverages. At this stage Coca-Cola defines their industry here. However over time companies can change their industry definition:o In the past Coca-Cola has defined their industry as:▪ Softdrinks, and at an earlier time as:• Cola MKT10007 Assignment 3 Guide to accompany template S2,15.docx !2 | P a g e o For the future Coca Cola has indicated that they intend widening their industry definition; in Australia they own Grinder’s Coffee and have introduced “Barista Brothers” cold coffee-flavoured...

Words: 796 - Pages: 4