Home » questions » how do I sort an array in java without using the predefined methods?

how do I sort an array in java without using the predefined methods?

2006-08-03 16:38:38, Category: Programming & Design
I am doing homework and I just cant do this.. I need to sort an array both ascending and descending.. If anyone has code for this.. I would really appreciate it!

Answers

  1. Steve T

    On 2006-08-03 18:04:35


    To simplest way to sort is to do the bubble sort. Bubble sort works by constantly finding the largest (or smallest, depending which way you are sorting) element, and moving it to the front. Then, starting at the back again, you move the next largest (or smallest) value behind this one and continue until you are done. This, while it works great, works in O(n^2) time, meaning every time you double the size of the array, the amount of time taken is 4x longer. A better way to do a sort is the quicksort. At worst it can take O(n^2) time, but it typically takes O(nlogn) time. Its explanation is a bit tricky, so i'd just read the attached wiki on it, but essentially it is an in-place sort that attempts to find the middle most value of the array (or portion its looking at), move all values larger than it to its right (higher indeces) and all values smaller to its left (lower indeces), then perform the same task on the numbers larger than this value and smaller than it. Yeah, read the wiki.