Write a Program That Read a Sequence of Integer Inputs and Print All Adjacent Duplicates

Simple comparison sorting algorithm

Chimera sort
Bubblesort-edited-color.svg

Static visualization of chimera sort[one]

Class Sorting algorithm
Information structure Array
Worst-case performance O ( n 2 ) {\displaystyle O(northward^{2})} comparisons, O ( n 2 ) {\displaystyle O(n^{ii})} swaps
Best-case performance O ( n ) {\displaystyle O(n)} comparisons, O ( 1 ) {\displaystyle O(1)} swaps
Average operation O ( n 2 ) {\displaystyle O(due north^{2})} comparisons, O ( north 2 ) {\displaystyle O(n^{2})} swaps
Worst-instance space complexity O ( due north ) {\displaystyle O(n)} total, O ( one ) {\displaystyle O(one)} auxiliary

Bubble sort, sometimes referred to as sinking sort, is a uncomplicated sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is a comparison sort, is named for the manner smaller or larger elements "chimera" to the top of the list.

This simple algorithm performs poorly in existent world use and is used primarily every bit an educational tool. More efficient algorithms such every bit quicksort, timsort, or merge sort are used past the sorting libraries built into popular programming languages such as Python and Java.[2] [3]

Analysis [edit]

An example of bubble sort. Starting from the outset of the list, compare every next pair, swap their position if they are not in the right society (the latter one is smaller than the former one). Subsequently each iteration, one less element (the last one) is needed to be compared until at that place are no more elements left to be compared.

Performance [edit]

Bubble sort has a worst-case and average complication of O ( n ii ) {\displaystyle O(northward^{2})} , where north {\displaystyle north} is the number of items being sorted. Virtually applied sorting algorithms have substantially better worst-instance or average complexity, often O ( northward log north ) {\displaystyle O(n\log n)} . Even other O ( n 2 ) {\displaystyle O(n^{ii})} sorting algorithms, such as insertion sort, generally run faster than chimera sort, and are no more complex. Therefore, bubble sort is not a practical sorting algorithm.

The only meaning advantage that chimera sort has over nearly other algorithms, even quicksort, only not insertion sort, is that the ability to detect that the list is sorted efficiently is built into the algorithm. When the list is already sorted (best-instance), the complexity of chimera sort is simply O ( n ) {\displaystyle O(n)} . By contrast, most other algorithms, even those with meliorate average-instance complexity, perform their entire sorting process on the set and thus are more circuitous. Notwithstanding, not only does insertion sort share this advantage, only information technology too performs better on a list that is substantially sorted (having a small number of inversions). Additionally, if this beliefs is desired, it can be trivially added to whatsoever other algorithm past checking the list before the algorithm runs.

Rabbits and Turtles [edit]

The distance and direction that elements must move during the sort make up one's mind bubble sort'southward operation considering elements move in different directions at different speeds. An element that must move toward the cease of the list can move chop-chop because information technology can take part in successive swaps. For example, the largest chemical element in the listing volition win every bandy, and then it moves to its sorted position on the commencement pass fifty-fifty if it starts almost the beginning. On the other hand, an chemical element that must move toward the beginning of the listing cannot motion faster than one step per laissez passer, so elements move toward the beginning very slowly. If the smallest element is at the end of the listing, it will have due north ane {\displaystyle n-ane} passes to motility it to the start. This has led to these types of elements being named rabbits and turtles, respectively, subsequently the characters in Aesop's fable of The Tortoise and the Hare.

Various efforts take been made to eliminate turtles to improve upon the speed of bubble sort. Cocktail sort is a bi-directional chimera sort that goes from beginning to end, and then reverses itself, going end to beginning. It can move turtles fairly well, but it retains O ( n two ) {\displaystyle O(n^{ii})} worst-case complexity. Comb sort compares elements separated by large gaps, and can motion turtles extremely quickly before proceeding to smaller and smaller gaps to smooth out the list. Its boilerplate speed is comparable to faster algorithms similar quicksort.

Step-by-pace example [edit]

Take an array of numbers "5 1 4 two 8", and sort the array from lowest number to greatest number using bubble sort. In each step, elements written in bold are being compared. Three passes will be required;

First Laissez passer
( five 1 4 ii 8 ) → ( 1 5 4 2 viii ), Here, algorithm compares the first 2 elements, and swaps since v > 1.
( 1 5 4 two 8 ) → ( 1 4 5 two eight ), Swap since 5 > 4
( 1 iv 5 ii eight ) → ( ane 4 2 v 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) → ( 1 four 2 5 8 ), At present, since these elements are already in order (8 > five), algorithm does non swap them.
Second Pass
( 1 four 2 5 8 ) → ( 1 iv two v 8 )
( 1 4 2 five 8 ) → ( 1 2 4 five 8 ), Swap since 4 > 2
( ane 2 4 5 eight ) → ( one 2 four 5 viii )
( 1 ii four v 8 ) → ( 1 2 4 v 8 )

Now, the array is already sorted, but the algorithm does not know if information technology is completed. The algorithm needs 1 additional whole pass without any swap to know it is sorted.

Third Laissez passer
( i 2 4 5 viii ) → ( 1 2 4 5 8 )
( one ii four 5 8 ) → ( 1 2 iv 5 8 )
( 1 2 4 5 8 ) → ( i 2 4 5 8 )
( 1 2 iv 5 8 ) → ( i 2 four 5 8 )

Implementation [edit]

Pseudocode implementation [edit]

In pseudocode the algorithm can be expressed as (0-based array):

                        procedure            bubbleSort            (            A            :            list            of            sortable            items            )            n            :=            length            (            A            )            echo            swapped            :=            false            for            i            :=            1            to            n            -            1            inclusive            practise            /*            if            this            pair            is            out            of            society            */            if            A            [            i            -            one            ]            >            A            [            i            ]            so            /*            swap            them            and            call up            something            changed            */            swap            (            A            [            i            -            ane            ]            ,            A            [            i            ])            swapped            :=            true            end            if            end            for            until            not            swapped            finish            procedure          

Optimizing chimera sort [edit]

The bubble sort algorithm can be optimized by observing that the n-thursday laissez passer finds the n-thursday largest element and puts it into its final place. And so, the inner loop can avoid looking at the last northward − 1 items when running for the n-th time:

                        procedure            bubbleSort            (            A            :            listing            of            sortable            items            )            n            :=            length            (            A            )            repeat            swapped            :=            false            for            i            :=            1            to            due north            -            1            inclusive            exercise            if            A            [            i            -            one            ]            >            A            [            i            ]            so            bandy            (            A            [            i            -            1            ]            ,            A            [            i            ])            swapped            :=            true            end            if            end            for            northward            :=            n            -            1            until            not            swapped            end            procedure          

More than generally, it tin can happen that more than than one element is placed in their final position on a single pass. In detail, after every pass, all elements after the last swap are sorted, and practise not demand to be checked again. This allows to skip over many elements, resulting in about a worst case 50% improvement in comparison count (though no improvement in swap counts), and adds very little complexity because the new code subsumes the "swapped" variable:

To accomplish this in pseudocode, the following tin can be written:

                        procedure            bubbleSort            (            A            :            list            of            sortable            items            )            north            :=            length            (            A            )            repeat            newn            :=            0            for            i            :=            1            to            north            -            1            inclusive            do            if            A            [            i            -            1            ]            >            A            [            i            ]            then            bandy            (            A            [            i            -            1            ]            ,            A            [            i            ])            newn            :=            i            end            if            end            for            due north            :=            newn            until            n                        1            finish            procedure          

Alternate modifications, such as the cocktail shaker sort endeavour to improve on the bubble sort performance while keeping the aforementioned idea of repeatedly comparing and swapping adjacent items.

Use [edit]

Chimera sort. The listing was plotted in a Cartesian coordinate arrangement, with each point (10, y) indicating that the value y is stored at alphabetize x. And so the list would exist sorted past bubble sort according to every pixel's value. Note that the largest end gets sorted first, with smaller elements taking longer to motion to their correct positions.

Although bubble sort is 1 of the simplest sorting algorithms to empathise and implement, its O(north 2) complexity ways that its efficiency decreases dramatically on lists of more than a small number of elements. Even amid simple O(northward 2) sorting algorithms, algorithms like insertion sort are usually considerably more than efficient.

Due to its simplicity, bubble sort is often used to introduce the concept of an algorithm, or a sorting algorithm, to introductory computer science students. Nonetheless, some researchers such every bit Owen Astrachan have gone to great lengths to disparage bubble sort and its continued popularity in informatics didactics, recommending that information technology no longer even be taught.[4]

The Jargon File, which famously calls bogosort "the archetypical [sic] perversely atrocious algorithm", also calls bubble sort "the generic bad algorithm".[5] Donald Knuth, in The Fine art of Estimator Programming, concluded that "the bubble sort seems to have nothing to recommend it, except a catchy proper noun and the fact that information technology leads to some interesting theoretical issues", some of which he then discusses.[6]

Bubble sort is asymptotically equivalent in running time to insertion sort in the worst example, but the two algorithms differ greatly in the number of swaps necessary. Experimental results such as those of Astrachan take also shown that insertion sort performs considerably amend even on random lists. For these reasons many modern algorithm textbooks avoid using the bubble sort algorithm in favor of insertion sort.

Bubble sort too interacts poorly with modern CPU hardware. It produces at least twice as many writes as insertion sort, twice as many cache misses, and asymptotically more than co-operative mispredictions.[ commendation needed ] Experiments by Astrachan sorting strings in Java show chimera sort to be roughly ane-fifth as fast equally an insertion sort and 70% every bit fast as a option sort.[iv]

In computer graphics bubble sort is popular for its capability to notice a very small error (similar bandy of just 2 elements) in almost-sorted arrays and set up information technology with just linear complexity (iin). For case, it is used in a polygon filling algorithm, where bounding lines are sorted past their x coordinate at a specific browse line (a line parallel to the x axis) and with incrementing y their lodge changes (two elements are swapped) just at intersections of two lines. Chimera sort is a stable sort algorithm, like insertion sort.

Variations [edit]

  • Odd–fifty-fifty sort is a parallel version of bubble sort, for bulletin passing systems.
  • Passes can exist from right to left, rather than left to correct. This is more than efficient for lists with unsorted items added to the end.
  • Cocktail shaker sort alternates leftwards and rightwards passes.

Debate over name [edit]

Bubble sort has been occasionally referred to every bit a "sinking sort".[vii]

For example, Donald Knuth describes the insertion of values at or towards their desired location as letting "[the value] settle to its proper level", and that "this method of sorting has sometimes been chosen the sifting or sinking technique.[viii]

This debate is perpetuated by the ease with which one may consider this algorithm from two different but every bit valid perspectives:

  1. The larger values might be regarded as heavier and therefore be seen to progressively sink to the bottom of the list
  2. The smaller values might be regarded as lighter and therefore exist seen to progressively bubble up to the top of the list.

In popular civilization [edit]

In 2007, former Google CEO Eric Schmidt asked then-presidential candidate Barack Obama during an interview almost the all-time way to sort one meg integers; Obama paused for a moment and replied: "I call back the chimera sort would be the wrong way to go."[nine] [10]

Notes [edit]

  1. ^ Cortesi, Aldo (27 April 2007). "Visualising Sorting Algorithms". Retrieved 16 March 2017.
  2. ^ "[JDK-6804124] (coll) Supercede "modified mergesort" in java.util.Arrays.sort with timsort - Java Bug System". bugs.openjdk.java.net . Retrieved 2020-01-11 .
  3. ^ Peters, Tim (2002-07-xx). "[Python-Dev] Sorting". Retrieved 2020-01-xi .
  4. ^ a b Astrachan, Owen (2003). "Chimera sort: an archaeological algorithmic analysis" (PDF). ACM SIGCSE Bulletin. 35 (ane): 1–five. doi:10.1145/792548.611918. ISSN 0097-8418.
  5. ^ "jargon, node: bogo-sort".
  6. ^ Donald Knuth. The Art of Computer Programming, Book 3: Sorting and Searching, Second Edition. Addison-Wesley, 1998. ISBN 0-201-89685-0. Pages 106–110 of department five.2.2: Sorting by Exchanging. "[A]lthough the techniques used in the calculations [to analyze the bubble sort] are instructive, the results are disappointing since they tell us that the bubble sort isn't actually very good at all. Compared to straight insertion […], bubble sorting requires a more complicated program and takes about twice equally long!" (Quote from the start edition, 1973.)
  7. ^ Black, Paul Eastward. (24 Baronial 2009). "chimera sort". Lexicon of Algorithms and Data Structures. National Institute of Standards and Engineering science. Retrieved 1 Oct 2014.
  8. ^ Knuth, Donald. The Art of Figurer Programming: Volume 3: Searching and Sorting. p. 80. ISBN0201896850.
  9. ^ Lai Stirland, Sarah (2007-11-14). "Obama Passes His Google Interview". Wired . Retrieved 2020-ten-27 .
  10. ^ Barack Obama, Eric Schmidt (Nov 14, 2007). Barack Obama | Candidates at Google (Youtube). Mountain View, CA 94043 The Googleplex: Talks at Google. Event occurs at 23:twenty. Archived from the original (Video) on September 7, 2019. Retrieved Sep 18, 2019. {{cite AV media}}: CS1 maint: location (link)

References [edit]

  • Thomas H. Cormen, Charles E. Leiserson, Ronald 50. Rivest, and Clifford Stein. Introduction to Algorithms, Second Edition. MIT Printing and McGraw-Loma, 2001. ISBN 0-262-03293-7. Problem 2-ii, pg.forty.
  • Sorting in the Presence of Co-operative Prediction and Caches
  • Fundamentals of Data Structures by Ellis Horowitz, Sartaj Sahni and Susan Anderson-Freed ISBN 81-7371-605-6
  • Owen Astrachan. Bubble Sort: An Archaeological Algorithmic Assay

External links [edit]

  • Martin, David R. (2007). "Animated Sorting Algorithms: Chimera Sort". Archived from the original on 2015-03-03. – graphical demonstration
  • "Lafore'due south Chimera Sort". (Java applet animation)
  • OEIS sequence A008302 (Tabular array (statistics) of the number of permutations of [north] that need k pair-swaps during the sorting)

williamsreartiong.blogspot.com

Source: https://en.wikipedia.org/wiki/Bubble_sort

0 Response to "Write a Program That Read a Sequence of Integer Inputs and Print All Adjacent Duplicates"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel