Built with Tutify.io

    AIStudyLabs

    Searching and Sorting Arrays

    Searching and Sorting Arrays

    Introduction

    In this lesson, we will delve into Searching and Sorting Arrays, two fundamental operations frequently used in programming. These operations are critical for efficiently managing and manipulating data within arrays. We will cover:

    Binary search and selection sort require a solid understanding of arrays, their indices, and the C programming language's syntax. Let’s get started!

    Linear Search

    Linear search is the simplest search algorithm, checking each element of the array sequentially until the desired element is found or the entire array has been searched. This search method is best suited for unsorted arrays.

    Linear Search Implementation:

    #include <stdio.h>
    
    int linearSearch(int arr[], int size, int target) {
        for (int i = 0; i < size; i++) {
            if (arr[i] == target) {
                return i; // Return the index if found
            }
        }
        return -1; // Return -1 if not found
    }
    
    int main() {
        int arr[] = {10, 20, 30, 40, 50};
        int size = sizeof(arr)/sizeof(arr[0]);
        int target = 30;
        int result = linearSearch(arr, size, target);
        if (result != -1) {
            printf("Element found at index: %d\n", result);
        } else {
            printf("Element not found in the array.\n");
        }
        return 0;
    }
    

    Output:

    Element found at index: 2
    

    Binary Search

    Binary search is a much more efficient search algorithm that applies only to sorted arrays. This algorithm repeatedly divides the search interval in half, thus reducing its time complexity.

    Binary Search Implementation:

    #include <stdio.h>
    
    int binarySearch(int arr[], int size, int target) {
        int left = 0, right = size - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) {
                return mid; // Element found
            } else if (arr[mid] < target) {
                left = mid + 1; // Move to the right half
            } else {
                right = mid - 1; // Move to the left half
            }
        }
        return -1; // Element not found
    }
    
    int main() {
        int arr[] = {10, 20, 30, 40, 50};
        int size = sizeof(arr)/sizeof(arr[0]);
        int target = 30;
        int result = binarySearch(arr, size, target);
        if (result != -1) {
            printf("Element found at index: %d\n", result);
        } else {
            printf("Element not found in the array.\n");
        }
        return 0;
    }
    

    Output:

    Element found at index: 2
    

    Selection Sort

    Selection sort is an in-place comparison sorting algorithm. It divides the input list into two parts: a sorted and an unsorted region. Initially, the sorted region is empty, and the algorithm selects the smallest element from the unsorted region and places it in the sorted region.

    Selection Sort Implementation:

    #include <stdio.h>
    
    void selectionSort(int arr[], int size) {
        for (int i = 0; i < size - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < size; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            // Swap the found minimum element with the first element of the unsorted part
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
        }
    }
    
    int main() {
        int arr[] = {64, 25, 12, 22, 11};
        int size = sizeof(arr)/sizeof(arr[0]);
        selectionSort(arr, size);
        printf("Sorted array: ");
        for (int i = 0; i < size; i++) {
            printf("%d ", arr[i]);
        }
        return 0;
    }
    

    Output:

    Sorted array: 11 12 22 25 64 
    

    Bubble Sort

    Bubble sort is another simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing adjacent elements and swapping them if they are in the wrong order. The algorithm gets its name because smaller elements 'bubble' to the top of the array.

    Bubble Sort Implementation:

    #include <stdio.h>
    
    void bubbleSort(int arr[], int size) {
        for (int i = 0; i < size - 1; i++) {
            for (int j = 0; j < size - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // Swap if the element is greater than the next
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    
    int main() {
        int arr[] = {64, 34, 25, 12, 22, 11, 90};
        int size = sizeof(arr)/sizeof(arr[0]);
        bubbleSort(arr, size);
        printf("Sorted array: ");
        for (int i = 0; i < size; i++) {
            printf("%d ", arr[i]);
        }
        return 0;
    }
    

    Output:

    Sorted array: 11 12 22 25 34 64 90 
    

    Comparing Searching and Sorting Algorithms

    Both searching and sorting algorithms have their time complexity and performance characteristics. For instance, linear search has a time complexity of O(n), while binary search reduces this to O(log n) for sorted arrays. In terms of sorting, selection and bubble sort have O(n²) complexity, making them inefficient for large datasets when compared to more advanced algorithms like quicksort or mergesort which operate at O(n log n).

    Summary / Key Takeaways

    In this lesson on Searching and Sorting Arrays, you have learned:

    C Programming Fundamentals: From Zero to Confident C Coder — Arrays and Strings

    Introduction to Programming and C

    Variables and Data Types

    Control Structures: Conditions and Loops

    Functions in C

    Arrays and Strings

    Working with Pointers

    File Handling in C

    Structures and Unions in C

    Project Development and Implementation

    Advanced C Concepts and Best Practices

    Tutorial Not Found