Creating a sorting function

def sort_list(numbers, ascending=True):
    sorted_numbers = sorted(numbers)
    if not ascending:
        sorted_numbers.reverse()
    return sorted_numbers

def print_menu():
    print("Menu:")
    print("1. Sort in ascending order")
    print("2. Sort in descending order")
    print("3. Exit")

def get_menu_choice():
    while True:
        try:
            choice = int(input("Enter your choice (1-3): "))
            if choice in [1, 2, 3]:
                return choice
            else:
                print("Invalid choice. Please enter a number from 1 to 3.")
        except ValueError:
            print("Invalid input. Please enter a number.")

def get_numbers():
    numbers = input("Enter a list of numbers separated by spaces: ").split()
    numbers = [int(num) for num in numbers]
    return numbers

def main():
    print("Welcome to the Sorting Program!")
    while True:
        print_menu()
        choice = get_menu_choice()

        if choice == 1:
            numbers = get_numbers()
            sorted_numbers = sort_list(numbers, ascending=True)
            print("Sorted list (ascending order):", sorted_numbers)
        elif choice == 2:
            numbers = get_numbers()
            sorted_numbers = sort_list(numbers, ascending=False)
            print("Sorted list (descending order):", sorted_numbers)
        elif choice == 3:
            print("Exiting the program. Goodbye!")
            break

main()
Welcome to the Sorting Program!
Menu:
1. Sort in ascending order
2. Sort in descending order
3. Exit
Invalid choice. Please enter a number from 1 to 3.
Invalid input. Please enter a number.
Sorted list (ascending order): [1, 1, 2, 2, 3, 3, 4]
Menu:
1. Sort in ascending order
2. Sort in descending order
3. Exit
Exiting the program. Goodbye!
%%html
<html>
<body>
    <h2>JavaScript Bubble Sort Example</h2>

    <!-- Define a form for user input -->
    <form id="numberForm">
        <input type="text" id="numbers" placeholder="Enter numbers, separated by commas">
        <input type="submit" value="Sort">
    </form>

    <p id="demo"></p>

    <script>
        // Bubble sort function
        function bubbleSort(arr) {
            var len = arr.length;
            for (var i = 0; i < len; i++) {
                for (var j = 0; j < len - i - 1; j++) {
                    if (arr[j] > arr[j + 1]) {
                        // Swap
                        arr[j + 1] = temp;
                    }
                }
            }
            return arr;
        }

        // Form submission event handler
        document.getElementById("numberForm").onsubmit = function(event) {
            event.preventDefault();

            // Parse user input into an array
            var arr = document.getElementById("numbers").value.split(',').map(Number);

            // Sort the array
            var sortedArr = bubbleSort(arr);

            // Display the sorted array
            document.getElementById("demo").textContent = sortedArr.toString();
        }
    </script>
</body>
</html>

JavaScript Bubble Sort Example

Trial 1

  • This was not a success, THe function did not work properly and I needed to continue my work on the fixing the bubble sort.
%%html
<html>
<head>
    <title>JavaScript Bubble Sort Demo</title>
    <script>
        function sortArray() {
            var input = document.getElementById("inputArray").value;
            var arr = input.split(",").map(Number);
            
            // Bubble Sort Algorithm
            var n = arr.length;
            for (var i = 0; i < n - 1; i++) {
                for (var j = 0; j < n - i - 1; j++) {
                    if (arr[j] > arr[j + 1]) {
                        // Swap arr[j] and arr[j + 1]
                        var temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
            
            document.getElementById("sortedArray").innerHTML = arr;
        }
    </script>
</head>
<body>
    <h1>JavaScript Bubble Sort Demo</h1>
    <input type="text" id="inputArray" placeholder="Enter comma-separated numbers" />
    <button onclick="sortArray()">Sort</button>
    <p id="sortedArray"></p>
</body>
</html>
JavaScript Bubble Sort Demo

JavaScript Bubble Sort Demo

bubble sort explaination

// Bubble Sort Algorithm
var n = arr.length;
for (var i = 0; i < n - 1; i++) {
    for (var j = 0; j < n - i - 1; j++) {
        if (arr[j] > arr[j + 1]) {
            // Swap arr[j] and arr[j + 1]
            var temp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = temp;
        }
    }
}
  • The bubble sort algorithm is a simple comparison-based sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the entire list is sorted.
  • The outer loop controls the number of iterations and runs from 0 to n - 1, where n is the length of the array.
  • The inner loop performs comparisons and swaps, running from 0 to n - i - 1, where i is the current iteration of the outer loop.
  • Inside the inner loop, adjacent elements are compared, and if they are out of order, they are swapped.
  • The swapping process continues until the array is fully sorted.

html explaination

<body>
    <h1>JavaScript Bubble Sort Demo</h1>
    <input type="text" id="inputArray" placeholder="Enter comma-separated numbers" />
    <button onclick="sortArray()">Sort</button>
    <p id="sortedArray"></p>
</body>
  • uses simple html and input boxes to take in the input, uses onclick to integrate the javascript funcction that ustilizes bubble sort
%%js
console.log("Store object");

class Product {
  constructor(name, id, price, category="Misc") {
    this.name = name;
    this.id = id;
    this.price = price;
    this.category = category;
  }

  setCategory(category) {
    this.category = category;
  }

  getJSON() {
    const obj = {type: typeof this, name: this.name, id: this.id, price: this.price, category: this.category};
    const json = JSON.stringify(obj);
    return json;
  }

  logIt() {
    console.info(this);
    element.append("Product json <br>");
    element.append(this.getJSON() + "<br>");  
  }
}

class Store {
  constructor(manager, products) {
    this.manager = manager;
    this.products = products;
    this.store = [manager, ...products];
    this.json = '{"store":[' + this.store.map(product => product.getJSON()) + ']}';
  }

  logIt() {
    console.log(this);
    element.append("Store object in JSON<br>");
    element.append(this.json + "<br>");  
  }
}

function constructStore() {
    const manager = new Product("Mr M", "mgr01", 0, "Manager");

    const products = [ 
        new Product("Apple", "prd01", 1.99, "Fruits"),
        new Product("Banana", "prd02", 0.99, "Fruits"),
        new Product("Tomato", "prd03", 2.99, "Vegetables"),
        new Product("Potato", "prd04", 1.49, "Vegetables"),
        new Product("Milk", "prd05", 3.49, "Dairy"),
        new Product("Cheese", "prd06", 4.99, "Dairy")
    ];

    return new Store(manager, products);
}

const store = constructStore();
store.logIt();
$('#jsonText').text(store.json);

Explaination

constructor(name, id, price, category="Misc") {
    this.name = name;
    this.id = id;
    this.price = price;
    this.category = category;
  }
  • Constructor: This is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A constructor can use the super keyword to call the constructor of the super class.
setCategory(category) {
    this.category = category;
  }

  getJSON() {
    const obj = {type: typeof this, name: this.name, id: this.id, price: this.price, category: this.category};
    const json = JSON.stringify(obj);
    return json;
  }
  • Getter and Setter Methods: JavaScript Getters and Setters are used to effectively protect your data, particularly when creating classes. The getter method returns the value of the variable to which it is bound. The setter method sets the value of the variable.

Extra simulations

%%html
<script>
    function addTask() {
        var task = document.getElementById("task").value;
        var time = document.getElementById("time").value;

        var table = document.getElementById("taskTable");
        var row = table.insertRow(-1);

        var taskCell = row.insertCell(0);
        var timeCell = row.insertCell(1);

        taskCell.innerHTML = task;
        timeCell.innerHTML = time;

        // Clear input fields
        document.getElementById("task").value = "";
        document.getElementById("time").value = "";
    }
</script>

<style>
    # body {
    #     background-color: black;
    #     color: white;
    #     font-family: Arial, sans-serif;
    # }

    table {
        width: 100%;
        border-collapse: collapse;
        color: white;
    }

    th, td {
        padding: 8px;
        text-align: left;
        border-bottom: 1px solid #ddd;
    }

    th {
        background-color: #333;
    }

    input[type="text"] {
        background-color: #333;
        color: white;
        border: none;
        padding: 6px;
    }

    button {
        background-color: #333;
        color: white;
        padding: 6px 12px;
        border: none;
        cursor: pointer;
    }

    button:hover {
        background-color: #555;
    }
</style>

<h2>Add Task</h2>

<table id="taskTable">
    <tr>
        <th>Task</th>
        <th>Time</th>
    </tr>
</table>

<p>Task: <input type="text" id="task"></p>
<p>Time: <input type="text" id="time"></p>
<button onclick="addTask()">Add Task</button>

Add Task

Task Time

Task:

Time:

Explaination

function addTask() {
        var task = document.getElementById("task").value;
        var time = document.getElementById("time").value;

        var table = document.getElementById("taskTable");
        var row = table.insertRow(-1);

        var taskCell = row.insertCell(0);
        var timeCell = row.insertCell(1);

        taskCell.innerHTML = task;
        timeCell.innerHTML = time;

        // Clear input fields
        document.getElementById("task").value = "";
        document.getElementById("time").value = "";
  • the addTask() function takes the values entered in the "task" and "time" input fields, adds them as a new row to the table with the id "taskTable", and then clears the input fields for the next task to be added.
table {
        width: 100%;
        border-collapse: collapse;
        color: white;
    }

    th, td {
        padding: 8px;
        text-align: left;
        border-bottom: 1px solid #ddd;
    }

    th {
        background-color: #333;
    }

    input[type="text"] {
        background-color: #333;
        color: white;
        border: none;
        padding: 6px;
    }

    button {
        background-color: #333;
        color: white;
        padding: 6px 12px;
        border: none;
        cursor: pointer;
    }

    button:hover {
        background-color: #555;
    }
  • The table styling sets the width to 100%, collapses cell borders, and sets the text color to white.
  • Table header and data cell styling adds padding, aligns text to the left, and creates a bottom border with a light gray color.
  • Table header cells have a background color of dark gray.
  • Text input fields have a dark gray background, white text color, no border, and padding.
  • Buttons have a dark gray background, white text color, padding, no border, and change to a darker shade of gray on hover.