gpt-4-1106-preview· OpenAI Arena Human Preference 55K
write a bubblesort implementation in lua
- User
write a bubblesort implementation in lua
- Assistant
Certainly! Below is an implementation of the Bubble Sort algorithm in Lua. Bubble Sort is a simple 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 list is sorted.
function bubbleSort(arr) local n = #arr local swapped repeat swapped = false for i = 2, n do if arr[i-1] > arr[i] then arr[i], arr[i-1] = arr[i-1], arr[i] swapped = true end end n = n - 1 until not swapped end -- Example usage: local array = {64, 34, 25, 12, 22, 11, 90} print("Unsorted array:") for _, v in ipairs(array) do io.write(v .. " ") end io.write("\n") bubbleSort(array) print("Sorted array:") for _, v in ipairs(array) do io.write(v .. " ") end io.write("\n")When you run this Lua script, it will sort the
arrayusing Bubble Sort and print both the unsorted and sorted versions to the console.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.