The bubble sort is generally considered to be the simplest sorting 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. 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.
Enjoy it :)
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Lets think this is the array we need to bubble sort | |
int[] arrayNum = {12,3,56,4,14,1,87,11}; | |
int sizeNum=arrayNum.Length; | |
int limit = sizeNum - 1; | |
//now we need to start 2 more loops, each holding the | |
//index of the previous loop | |
for (int j = 0; j < sizeNum - 1; j++) | |
{ | |
for (int k = 0; k < limit-j ; k++) | |
{ | |
//check if the index of the inner loop of the array | |
//matches the inner loops index of the array + 1 | |
if (arrayNum[k] > arrayNum[k + 1]) | |
{ | |
//now we will do our sorting. we will set | |
//the index of the inner loop to our finalNum | |
//variable, then set the index of the array to the | |
//index plus 1 | |
int finalNum = arrayNum[k]; | |
arrayNum[k] = arrayNum[k + 1]; | |
arrayNum[k + 1] = finalNum; | |
} | |
} | |
} | |
//now we will print out the final sorted array | |
Console.WriteLine("----------------------------------"); | |
Console.WriteLine("Bubble Sort results:"); | |
//loop through the sorted array and print out the values | |
for (int l = 0; l < sizeNum; l++) | |
{ | |
Console.WriteLine(arrayNum[l]); | |
} | |
Console.Read(); |
Enjoy it :)
No comments:
Post a Comment