o4-mini-2025-04-16· OpenAI
LMArena Human Preference 140K
Write me a quick sort algorithm using javascript
- User
Write me a quick sort algorithm using javascript
- Assistant
Here’s a concise, ES6-style Quick Sort implementation in JavaScript. It returns a new sorted array (non-in-place):
/** * Quick Sort (functional, not in-place) * @param {number[]} arr — array of numbers to sort * @returns {number[]} sorted array */ const quickSort = arr => { // Base case: 0 or 1 element is already “sorted” if (arr.length < 2) return arr; // Choose pivot (here: middle element) const pivotIndex = Math.floor(arr.length / 2); const pivot = arr[pivotIndex]; // Partition into < pivot, == pivot, > pivot const less = []; const equal = []; const greater = []; for (const x of arr) { if (x < pivot) less.push(x); else if (x > pivot) greater.push(x); else equal.push(x); } // Recursively sort partitions and concatenate return [ ...quickSort(less), ...equal, ...quickSort(greater) ]; }; // Example usage: const nums = [9, -3, 5, 2, 6, 8, -6, 1, 3]; console.log(quickSort(nums)); // Output: [ -6, -3, 1, 2, 3, 5, 6, 8, 9 ]
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.