起泡排序算法
Bubble Sort is a simple algorithm which is used to sort a given set of n
elements provided in form of an array with n
number of elements. Bubble Sort compares all the element one by one and sort them based on their values.
冒泡排序是一个简单的算法,其用于一组给定的排序n
在与阵列的形式提供要素n
元素的个数。 Bubble Sort会一一比较所有元素,然后根据它们的值对它们进行排序。
If the given array has to be sorted in ascending order, then bubble sort will start by comparing the first element of the array with the second element, if the first element is greater than the second element, it will swap both the elements, and then move on to compare the second and the third element, and so on.
如果给定数组必须按升序排序,则冒泡排序将通过将数组的第一个元素与第二个元素进行比较来开始,如果第一个元素大于第二个元素,它将交换两个元素,然后继续比较第二个和第三个元素,依此类推。
If we have total n
elements, then we need to repeat this process for n-1
times.
如果总共有n
元素,则需要重复此过程n-1
次。
It is known as bubble sort, because with every complete iteration the largest element in the given array, bubbles up towards the last place or the highest index, just like a water bubble rises up to the water surface.
之所以称为气泡排序 ,是因为在每次完整迭代中,给定数组中的最大元素都会将气泡向上气泡到最后一个位置或指向最高索引,就像气泡上升到水面一样。
Sorting takes place by stepping through all the elements one-by-one and comparing it with the adjacent element and swapping them if required.
排序是通过一步一步地遍历所有元素并将其与相邻元素进行比较,并在需要时进行交换来进行的。
实现冒泡排序算法 (Implementing Bubble Sort Algorithm)
Following are the steps involved in bubble sort(for sorting a given array in ascending order):
以下是气泡排序所涉及的步骤(用于按给定的数组升序排序):
Starting with the first element(index = 0), compare the current element with the next element of the array.
从第一个元素(索引= 0)开始,将当前元素与数组的下一个元素进行比较。
If the current element is greater than the next element of the array, swap them.
如果当前元素大于数组的下一个元素,请交换它们。
If the current element is less than the next el