Hi guys, I'm constructing a program in which I generate a random array of 1000 integers, and then sort them via three methods, Bubble Sort, Insertion Sort and Quick Sort and then calculate the time of execution. I have managed to finish the majority of the program, however I'm having a problem in trying to overwrite the sorted array with the unsorted one in order to pass it down to the next method, in order to have fair execution times. I managed to copy the unsorted array, however all I need to do now is overwrite, do any of you have any suggestions please?
My, there’s some hard to read code there. Single-letter identifiers should only be used for loop indices or formal type parameters.
Do you really want to print “this is the unsorted array” 1000 times?
You ought not to try to pass the size of an array as an argument, but should always use the array’s length field directly inside the method.
What is wrong with using the clone() method on your array? It returns a shallow copy, but when the elements are primitives, that will be all right. Why overwrite the arrays? Why not simply clone it twice, and you will then have three copies.
By the way: for a 1000-element array the millisecond method probably doesn’t have a fine enough granularity for your timing. There is a System class (static) method which returns nanoseconds or some approximation to nanoseconds. You will probably have to use that.
That is because you have put them in their own block and they have gone out of scope. By the way: you need to clone each new array once, not 1000 times!
Oops, my bad, thanks for pointing that out. Regarding the method you referred to about nanoseconds, do you mind explaining, as the time of executions are all the same.
Some suggestions to make your code easier to read:
Apply indentation of code consistently. Indentation should reflect the code structure, making it easier to read and understand.
Always, always use {} braces for loops and conditionals, even if there is only one line of instruction inside the braces.
Repetitious code should be refactored, extracting the repeated lines into a method.
Yes, the language allows you to declare and initialize multiple variables on a single line. But don't.