Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to sort an array of names is to use a sorting algorithm, such as bubble sort, insertion sort, or quicksort. These algorithms compare pairs of elements in the array and swap them if they are not in the correct order, repeatedly until the entire array is sorted.

To sort an array of names, you would need to define a comparison function that compares two names and determines their order. For example, you might compare the names based on their alphabetical order, or based on some other criteria (e.g. length of the name, number of vowels, etc.).

Here is an example of how you might sort an array of names using the bubble sort algorithm in JavaScript:

// Example array of names
let names = ["Alice", "Bob", "Charlie", "David", "Eleanor"]

// Comparison function
function compareNames(a, b) {
  if (a < b) {
    return -1
  }
  if (a > b) {
    return 1
  }
  return 0
}

// Bubble sort algorithm
for (let i = 0; i < names.length - 1; i++) {
  for (let j = 0; j < names.length - i - 1; j++) {
    if (compareNames(names[j], names[j+1]) > 0) {
      // Swap the elements
      let temp = names[j]
      names[j] = names[j+1]
      names[j+1] = temp
    }
  }
}

// Resulting array of names (sorted)
console.log(names)   // ["Alice", "Bob", "Charlie", "David", "Eleanor"]

In this example, the compareNames function compares two names (a and b) and returns -1 if a comes before b, 1 if a comes after b, and 0 if they are equal. The bubble sort algorithm repeatedly compares pairs of adjacent elements in the array and swaps them if they are not in the correct order, until the entire array is sorted. The resulting array of names is printed to the console.