40 views

Uploaded by Giezel Revis

,

,

Attribution Non-Commercial (BY-NC)

- ISC Class XII Computer Science Project JAVA Programs
- Algorithm Analysis Cheat Sheet
- IGNOU MCA MCS-031 Solved Assignment 2010
- Week 7 Notes
- Understanding Explain
- Analysis and Implementation of a Data Pre-processing System
- Programming Pearls - Self-Describing Data
- [Google Interview Prep Guide] Site Reliability Manager (SRM) (1)
- Programming 1 Final Machine Problem
- Ada Tutorials
- 09 Advanced Process Panel 60
- SJBIT(Design and Analysis of Algorithm lab Manual)
- Iceberg
- Performance Tuning of Datastage Parallel Jobs
- Sorting
- 0478 Pseudocode Guide
- Lecture 21
- 5a Sorting
- Soft Dev
- Lecture-1-CS210-2012 (1).pptx

You are on page 1of 10

In the bubble sort, as elements are sorted they gradually "bubble" (or rise) to their proper location in the array, like bubbles rising in a glass of soda. The bubble sort repeatedly compares adjacent elements of an array. The first and second elements are compared and swapped if out of order. Then the second and third elements are compared and swapped if out of order. This sorting process continues until the last two elements of the array are compared and swapped if out of order.

When this first pass through the array is complete, the bubble sort returns to elements one and two and starts the process all over again. So, when does it stop? The bubble sort knows that it is finished when it examines the entire array and no "swaps" are needed (thus the list is in proper order). The bubble sort keeps track of occurring swaps by the use of a flag.

The table below follows an array of numbers before, during, and after a bubble sort for descending order. A "pass" is defined as one full trip through the array comparing and if necessary, swapping, adjacent elements. Several passes have to be made through the array before it is finally sorted.

Array at beginning: After Pass #1: 84 After Pass #2: 84 After Pass #3: 86 After Pass #4: 94 After Pass #5 (done):

84 76 86 94 91 94

69 86 94 91 86 91

76 94 91 84 84 86

86 91 76 76 76 84

94 69 69 69 69 76

91

69

The bubble sort is an easy algorithm to program, but it is slower than many other sorts. With a bubble sort, it is always necessary to make one final "pass" through the array to check to see that no swaps are made to ensure that the process is finished. In actuality, the process is finished before this last pass is made.

// Bubble Sort Function for Descending Order void BubbleSort(apvector <int> &num) { int i, j, flag = 1; // set flag to 1 to start first pass int temp; // holding variable

int numLength = num.length( ); for(i = 1; (i <= numLength) && flag; i++) { flag = 0; for (j=0; j < (numLength -1); j++) { if (num[j+1] > num[j]) { temp = num[j]; num[j] = num[j+1]; num[j+1] = temp; flag = 1; } } } return; //arrays are passed to functions by address; nothing is returned } // indicates that a swap occurred. // swap elements // ascending order simply changes to <

/* Bubble sort code */ #include <stdio.h> int main() { int array[100], n, c, d, swap; printf("Enter number of elements\n"); scanf("%d", &n); printf("Enter %d integers\n", n); for (c = 0; c < n; c++) scanf("%d", &array[c]); for (c = 0 ; c < { for (d = 0 ; d { if (array[d] { swap array[d] array[d+1] } } } ( n - 1 ); c++) < n - c - 1; d++) > array[d+1]) /* For decreasing order use < */ = array[d]; = array[d+1]; = swap;

printf("Sorted list in ascending order:\n"); for ( c = 0 ; c < n ; c++ ) printf("%d\n", array[c]); return 0; }

Bubble Sort

Bubble sort is a simple and well-known sorting algorithm. It is used in practice once in a blue moon and its main application is to make an introduction to the sorting algorithms. Bubble sort belongs to O(n 2) sorting algorithms, which makes it quite inefficient for sorting large data volumes. Bubble sort is stable and adaptive.

Algorithm

1. Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them. 2. If at least one swap has been done, repeat step 1. You can imagine that on every step big bubbles float to the surface and stay there. At the step, when no bubble moves, sorting stops. Let us see an example of sorting an array to make the idea of bubble sort clearer. Example. Sort {5, 1, 12, -5, 16} using bubble sort.

Complexity analysis

Average and worst case complexity of bubble sort is O(n 2). Also, it makes O(n 2) swaps in the worst case. Bubble sort is adaptive. It means that for almost sorted array it gives O(n) estimation. Avoid implementations, which don't check if the array is already sorted on every step (any swaps made). This check is necessary, in order to preserve adaptive property.

One more problem of bubble sort is that its running time badly depends on the initial order of the elements. Big elements (rabbits) go up fast, while small ones (turtles) go down very slow. This problem is solved in the Cocktail sort. Turtle example. Thought, array {2, 3, 4, 5, 1} is almost sorted, it takes O(n 2) iterations to sort an array. Element {1} is a turtle.

Rabbit example. Array {6, 1, 2, 3, 4, 5} is almost sorted too, but it takes O(n) iterations to sort it. Element {6} is a rabbit. This example demonstrates adaptive property of the bubble sort.

Code snippets

There are several ways to implement the bubble sort. Notice, that "swaps" check is absolutely necessary, in order to preserve adaptive property.

Java

public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp;

while (swapped) { swapped = false; j++; for (int i { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } } = 0; i < arr.length j; i++)

C++

void bubbleSort(int arr[], int n) { bool swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < n - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; }

} } }

- ISC Class XII Computer Science Project JAVA ProgramsUploaded byTed
- Algorithm Analysis Cheat SheetUploaded byeplusie
- IGNOU MCA MCS-031 Solved Assignment 2010Uploaded byGunjan Saxena
- Week 7 NotesUploaded bytest
- Understanding ExplainUploaded byCúc Ku Harry
- Analysis and Implementation of a Data Pre-processing SystemUploaded byEditor IJRITCC
- Programming Pearls - Self-Describing DataUploaded byVikash Singh
- [Google Interview Prep Guide] Site Reliability Manager (SRM) (1)Uploaded byPéterFarkas
- Programming 1 Final Machine ProblemUploaded byjbert
- Ada TutorialsUploaded byYogenderBhardwaj
- 09 Advanced Process Panel 60Uploaded byLuis Felipe Martinez
- SJBIT(Design and Analysis of Algorithm lab Manual)Uploaded byJayanth Vasudev
- IcebergUploaded byManoj Kumar G
- Performance Tuning of Datastage Parallel JobsUploaded byನಾಗಾಭರಣ ವಿ ಜಿ
- SortingUploaded byFatima Shakeel
- 0478 Pseudocode GuideUploaded byStevie
- Lecture 21Uploaded byMujeeb Laghari
- 5a SortingUploaded byAjay Kaundal
- Soft DevUploaded byCristy Balubayan Nazareno
- Lecture-1-CS210-2012 (1).pptxUploaded byMoazzam Hussain
- data structures question bankUploaded byAnand Kumar
- dsUploaded bykrishna kumar
- Lecture 4 QuicksortUploaded byMark Williams
- dds docu.rtfUploaded bySounak Banerjee
- QuickSortsUploaded byManoj Kumar G
- 1004_3Uploaded byAnonymous G3E3ODfC
- 745390498Uploaded bymiketol
- 351Uploaded byRon Tonkamo
- C_chap06.pptUploaded bySrinidhi Upadhya
- 24 Write a Program Using Parallel Arrays to Represent the Following Student DatabaseUploaded byAlexis V. Larosa

- EnhancednmUploaded byGiezel Revis
- Book1Uploaded byGiezel Revis
- MP3Uploaded byGiezel Revis
- ted-talksUploaded byGiezel Revis
- PrintqUploaded byGiezel Revis
- Batac EmpanadaUploaded byGiezel Revis
- 13 MonolithicUploaded byAbdul Razzak
- 24854_TORSION_2Uploaded byGiezel Revis
- Solved Example Clockple on Angle of ElevationUploaded byGiezel Revis
- 5th grade worksheets.pdfUploaded byGiezel Revis
- Pytel Mechanics.of.Materials.2e SolutionsUploaded byks_edwin
- Decimal Number Review 0-40Uploaded byGiezel Revis
- AbstractUploaded byGiezel Revis
- ComputerFUploaded byGiezel Revis
- 24191_FrontPage_SY2015-2016 (1)Uploaded byGiezel Revis
- Portfolio in Fm LabUploaded byGiezel Revis
- University of the EastUploaded byGiezel Revis
- Lab Report FormatUploaded byGiezel Revis
- 24359_Problem+Set+Applications_1Uploaded byGiezel Revis
- APPLICATIONSUploaded byGiezel Revis
- CircuitsUploaded byGiezel Revis
- mechanicsUploaded byceelyn
- Intoduction+to+Safety+ManagementUploaded byGiezel Revis
- 1khgkUploaded byGiezel Revis
- 1Uploaded byGiezel Revis
- Diode Approx Exam1Uploaded byGiezel Revis
- Lecture10(Static)Uploaded byGiezel Revis
- SemiconductorsUploaded byGiezel Revis
- Electronic Device Lecture2Uploaded byGiezel Revis

- Cusb Research MethodologyUploaded byPritam Ananta
- DalekUploaded byWilliam Myers
- Physician PowerChart Training Manual v3Uploaded byyosty
- AVH-X1680DVD.pdfUploaded bypaulorato
- Methods of ReproductionUploaded bycmillica1176
- Fawaz FM.pdfUploaded bySameer Amjad
- 98a7aa_541c045a2e6d4268bd4b4031287ed30eUploaded byKarlos Daniel Barros
- 54-462-1-PB.pdfUploaded byPearl Sky
- Resume NarumolUploaded byapi-26134334
- b.com III Yr Syllabus Semester v and ViUploaded bymanojpatil186
- mNC Role in RetailingUploaded byThulasi Brindha
- Physics history (science)Uploaded bydsk123dk
- 3015Uploaded byDharmendra Sumitra Upadhyay
- Indonesia: Decentralized Health Services ProjectUploaded byIndependent Evaluation at Asian Development Bank
- UCIl ReportUploaded bySuryaKanth
- Purcell Gates TDPT Paper FINALUploaded byRobertGutunoiu
- mockcat-7oneUploaded byTejashwi Kumar
- l Uk FlowtrueUploaded bysanjeevvange
- fulltextUploaded byوائل عبده
- Zener-diode12-1Uploaded byWaka Sama
- Document 1Uploaded byDerifa Yunifal
- Overhead Conductor TypesUploaded byHumayun Ahsan
- ansys tutoUploaded byசெல்வ குமார்
- 5833506.pdfUploaded byIsaGürkanMeral
- ch 3 review sheetUploaded byapi-233611431
- Zizek_2018_How Mao Would Have Evaluated the Yellow Vests – Slavoj ZizekUploaded byAndré Luís Mattedi Dias
- Biology Investigatory Project (on eye diseases)Uploaded bydiya
- Finishing Occlusion 2Uploaded byPae Anusorn Amtanon
- activity1 9designinnovationUploaded byapi-325676907
- 22. fisika KuantumUploaded byRizna Nofitasari