1 / 9

Array Sort

This guide covers the implementation of the Bubble Sort algorithm in C programming language. It demonstrates how the sorting process uses iterations and passes to organize an array of integers. The example starts with an array of five elements arranged in descending order and sorts them through multiple passes. Each pass incrementally compares adjacent elements, swapping them if they are in the wrong order. The implementation includes functions for swapping elements and printing the sorted array at the end.

sybil-nunez
Télécharger la présentation

Array Sort

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Array Sort

  2. Sort Pass 1

  3. Sort Pass 2

  4. Sort Pass 3

  5. Sort Pass 4

  6. Bubble Sort - Iterations • 5 elements in array • 4 passes and 4, 3, 2, and 1 iterations • Total 10 • N elements in array • N-1 passes, and N-1, N-2, …, 2, 1 iterations

  7. Implementation - 1 • #include <stdio.h> • int main(void) { • inti, j; • int temp, a[5] = {5, 4, 3, 2, 1}; • for(i=0; i<4; i++) { • for(j=0; j<4-i; j++) { • if(a[j] > a[j+1]) { • temp = a[j]; • a[j] = a[j+1]; • a[j+1] = temp; • } • } • } • for(i=0; i<5; i++) printf("%d ", a[i]); • printf("\n"); • return(0); • }

  8. Implementation - 2 • #include <stdio.h> • void Xchange(int*a, int *b); • int main(void) { • inti, j; • int a[5] = {5, 4, 3, 2, 1}; • for(i=0; i<4; i++) { • for(j=0; j<4-i; j++) { • if(a[j] > a[j+1]) Xchange(&a[j], &a[j+1]); • } • } • for(i=0; i<5; i++) printf("%d ",a[i]); • printf("\n"); • return(0); • } • void Xchange(int *a, int *b) { • int temp; • temp = *a; • *a = *b; • *b = temp; • }

  9. Implementation - 3 • #include <stdio.h> • void Xchange(int*a, int *b); • void PrintArr(intn, int a[]); • int main(void) { • inti, j; • int a[5] = {5, 4, 3, 2, 1}; • for(i=0; i<4; i++) { • for(j=0; j<4-i; j++) • if(a[j] > a[j+1]) • Xchange(&a[j], &a[j+1]); • } • PrintArr(5, a); • return(0); • } • void Xchange(int*a, int *b) { • int temp; • temp = *a; • *a = *b; • *b = temp; • } • void PrintArr(intn, int a[]) { • inti; • for(i=0; i<n; i++) printf("%d ",a[i]); • printf("\n"); • }

More Related