--> Skip to main content

Total Pageviews

CT Week 6

Sorting Algorithms and Lists

πŸ“š Sorting Algorithms and Lists

List of Lists

A list of lists is a data structure where each element in the main list is itself a list. This allows for the creation of complex, multi-dimensional arrays. For example, a list of lists can be used to represent a matrix or a table where each sublist is a row.

Insertion Sort

Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much like sorting playing cards in your hands. The algorithm iterates through the list, growing the sorted portion behind it. At each iteration, it removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.

Ordered List

An ordered list is a list in which the items are numbered and the order matters. In HTML, it is created using the

    tag. Each item in the list is defined with the
  1. tag. Ordered lists are useful for displaying items in a specific sequence, such as steps in a process or rankings.

    Insertion Sort Code

    
    function insertionSort(arr) {
        for (let i = 1; i < arr.length; i++) {
            let key = arr[i];
            let j = i - 1;
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = key;
        }
    }
    
        

    Explanation: The insertion sort algorithm sorts an array by iteratively inserting each element into its correct position in a sorted portion of the array.

    Ordered List Code

    
    function addToOrderedList(list, item) {
        if (list.length === 0) {
            list.push(item);
        } else {
            for (let i = 0; i < list.length; i++) {
                if (item < list[i]) {
                    list.splice(i, 0, item);
                    return;
                }
            }
            list.push(item);
        }
    }
    
        

    Explanation: The ordered list function inserts an item into its correct position in a sorted list, maintaining the order of the list.

    GA:

Comments