Sunday November 10th, 2019

Bubble Sort

By Ebubekir Sezer

Hello, In my previous articles, I wrote about the Insertion and Selection Sort Algorithms. In this article, I will try to make Bubble Sort Algorithm. In the bubble sort, we are finding the bigger item in the array and then change the order, algorithm do these process until the array become orderly. For the give an example, think like that array = [3,1,6,5,7,8,2,4] for the make orderly see the below process.

3,1,6,5,7,8,2,4 -> items compared and algorithm change the order if bigger in the false order.

3,1,6,5,7,8,2,4 -> 3,1,6,5,7,2,8,4 -> 3,1,6,5,2,7,8,4 -> 3,1,6,2,5,7,8,4 -> 3,1,2,6,5,7,8,4 -> 3,1,2,6,5,7,8,4 -> 1,3,2,6,5,7,8,4

Process goes until the array become orderly.

C Code:

#include<stdio.h>

void bubbleSort(int array[],int size){
	int temp;
	
	for(int i=0;i<size;i++){
		for(int j = size-1;j>i;j--){
			if(array[j-1]>array[j]){
				temp = array[j-1];
				array[j-1]= array[j];
				array[j] = temp;
			}
		}
	}
}

void maxToMin(int array[],int size){
	
	int temp;
	for(int i=0;i<size;i++){
		for(int j=size-1;j>i;j--){
			if(array[j-1]<array[j]){
				temp = array[j-1];
				array[j-1] = array[j];
				array[j] = temp;
			}
		}
	}
}

int main(){
	int array[] = {3,1,6,5,7,8,2,4};
	int size = sizeof(array)/sizeof(array[0]);
	
	bubbleSort(array,size);
	
	for(int i = 0;i<size;i++){
		printf("%d ",array[i]);
	}
	printf("\n");
	int myarray[] = {3,1,6,5,7,8,2,4};
	int mysize = sizeof(array)/sizeof(array[0]);
	
	maxToMin(myarray,mysize);
	for(int i = 0;i<mysize;i++){
		printf("%d ",myarray[i]);
	}
}

Python Code:

def bubbleSort(array):
    for i in range(len(array)):
        for j in range(0,len(array)-i-1):
            if array[j]>array[j+1]:
                array[j+1],array[j] = array[j],array[j+1]

def maxToMin(array):
    for i in range(len(array)):
        for j in range(0,len(array)-i-1):
            if array[j]<array[j+1]:
                array[j+1],array[j] = array[j],array[j+1]

array = [3,1,6,5,7,8,2,4]
bubbleSort(array)
print("Bubble Sort")
for i in range(len(array)):
    print("%d "%array[i])
    
array = [3,1,6,5,7,8,2,4]
maxToMin(array)
print("Max to Min")
for i in range(len(array)):
    print("%d" %array[i])

You can ask your questions via e-mail or comments.