Sorting algorithms/Bubble sort: Difference between revisions

m
Got rid of algorithm and examples separation, superficially fixed the algorithm description
(Added D example)
m (Got rid of algorithm and examples separation, superficially fixed the algorithm description)
Line 1:
{{task}}{{Sorting Algorithm}}
{{Sorting Algorithm}}
 
In this task, the goal is to sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
 
The '''bubble sort''' is generally considered to be the simplest sorting algorithm. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n<sup>2</sup>) performance, it is never used anywhere else.
=Algorithm=
 
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them). Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass. (Large values "bubble" rapidly toward the end, pushing others down around them.) A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
The '''bubble sort''' is generally considered to be the simplest sorting algorithm. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n<sup>2</sup>) performance, it is never used anywhere else.
 
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions. Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass. (Large values "bubble" rapidly toward the end, pushing others down around them.) A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
 
This can be expressed in pseudocode as follows (assuming 1-based indexing):
Line 19 ⟶ 15:
set hasChanged to true
until hasChanged is false
 
=Examples=
 
=={{header|Ada}}==
Anonymous user