Bubble Sort using Call by Reference (Pointers) C Program

In one of our previous posts we already discussed about Bubble Sort algorithm and how to implement it in C programming. In this post we will discuss about bubble sort using call by reference method. In other words we will implement the bubble sort algorithm using pointers i.e call by reference.

[js]

#include <stdio.h>
#define SIZE 10
void bubbleSort(int * const array, const int size);
void swap(int *element1Ptr, int *element2Ptr);
int main(void){

int arr[SIZE] = {2, 3, 9, 4, 1, 5, 7, 12, 18, 15};

printf("Original array valuesnn");
for(int i=0; i<SIZE; i++){
printf("%dn", arr[i]);
}

bubbleSort(arr, SIZE);

printf("nnSorted array valuesnn");
for(int i=0; i<SIZE; i++){
printf("%dn", arr[i]);
}

}

void bubbleSort(int * const array, const int size){
int pass, i=0;

for(pass=0; pass < size-1; pass++){

for(i=0; i < size-1; i++){

if(array[i] > array[i+1]){
swap(&array[i], &array[i+1]);
}
}
}
}

void swap(int *element1Ptr, int *element2Ptr){
int hold;
hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
}

[/js]

Output:

2 thoughts on “Bubble Sort using Call by Reference (Pointers) C Program

Leave a Comment

Your email address will not be published.