Median In a Row-Wise sorted Matrix

Question :

We are given a row wise sorted matrix of size r * c, we need to find the median of the matrix given. It is assumed that r*c is always odd.

Constraints :

1<= T <=100

1<= r,c <=150

1<= a[i][j] <=1000

Input :

The first line of input contains an integer T denoting the number of test cases. Each test case contains two integers r and c, where r is the number of rows and c is the number of columns in the array a[]. Next r line contains space separated c elements each in the array a[].​

Output :

Print an integer which is the median of the matrix.

Sample TestCase :

Input :

1

3 3

1 3 5

2 6 9

3 6 9

Output :

5

Solution :

package main

import "fmt"

func main(){
	var t int
	fmt.Scan(&t)
	for i:=0; i<t; i++ {
		var r, c, temp, x int
		fmt.Scan(&r)
		fmt.Scan(&c)
		x = 0
		var a []int
		for j:=0; j<r; j++ {
			for k:=0; k<c; k++ {
				fmt.Scan(&temp)
				a = append(a, temp)
				x++
			}
		}
		n := r*c
	    flag := true
	    for flag {
	        flag = false
	        for i := 1; i < n-1; i++ {
	            if a[i-1] > a[i] {
	                a[i], a[i-1] = a[i-1], a[i]
	                flag = true
	            }
	        }
	    }
		fmt.Println(a[x/2])
	}
}