Program:
#include <xc.h> void main(void) { int i, j, key, temp, flag = 0, choice; int arr[] = { 4, 1, 3, 5, 2 }; TRISB = 2; PORTB = 0x03; choice = 3; switch (choice) { case 1: { //bubble sort for (i = 1; i < 5; i++) { for (j = 0; j < 5 - i; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; flag = 1; } } if (flag == 0) { break; } } break; } case 2: { //descending order for (i = 1; i < 5; i++) { for (j = 0; j < 5 - i; j++) { if (arr[j] < arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; flag = 1; } } if (flag == 0) { break; } } break; } case 3: { for (i = 1; i < 5; i++) { key = arr[i]; j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } break; } case 4: { for (i = 1; i < 5; i++) { key = arr[i]; j = i - 1; while (j >= 0 && arr[j] < key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } break; } } TRISB = 0; for (i = 0; i < 5; i++) { PORTB = arr[i]; } return; }
Output:
Fig: Variable Address
Fig: Before Sorting Array
Fig: After Sorting Array