Groovy web console

subscribe to the feed Subscribe
to this
site
sort (via #groovywebconsole)
tweet this snippet Tweet
this
script

sort

Published 7 months ago by Anonymous
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def createArray() {
    def arr = new int[10] [10]
    Random random = new Random()
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            arr[i][j] = random.nextInt(10)
        }
    }
    arr
}

def printArray(int[][] array) {
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            print(array[i][j] + ' ')
        }
        println('')
    }
}

def sortArray(int[][] array) {
    for (int i = 0; i < 10; i++) {
        int[] arr = array[i]
        int counter = 1 // set counter to 1 to enter loop
        while (counter != 0) {
            counter = 0
            for (int j = 0; j < 9; j++) {
                int nextElement = arr[j + 1]
                int currentElement = arr[j]
                if (nextElement < currentElement) {
                    arr[j] = nextElement
                    arr[j + 1] = currentElement
                    counter++
                }
            }
        } 
        
    }
}
int[][] array = createArray()
sortArray(array)
printArray(array)