Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 23rd, 2012  |  syntax: None  |  size: 1.40 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. package main
  2. import(
  3.         "os"
  4.         "io"
  5.         "bufio"
  6.         "fmt"
  7.         "strconv"
  8. )
  9.  
  10.  
  11. var (
  12.         data []int
  13.         counter int=0
  14.         filename string="testnum.txt"
  15. )
  16.  
  17. func swap( arr []int,i int, j int){
  18.         arr[i],arr[j]=arr[j],arr[i]
  19. }
  20. func quicksort(a []int) {
  21.         if len(a)>1 {
  22.                 pivotIndex:=0
  23.                 pivotIndex=partition(a,pivotIndex)
  24.                 left:=a[:pivotIndex]
  25.                 counter=counter+len(left)-1
  26.                 right:=a[pivotIndex+1:]
  27.                 counter=counter+len(right)-1
  28.                 quicksort(left)
  29.                 quicksort(right)
  30.         }
  31. }
  32.  
  33. func partition(a []int, pivotIndex int) int {
  34.         rightIndex:=len(a)-1
  35.         pivotValue:=a[pivotIndex]
  36.         i:=pivotIndex+1 // i is the lower index,j is the upper index
  37.         for j:=pivotIndex+1;j<rightIndex;j++ {
  38.                 if a[j]<pivotValue {
  39.                         swap(a,i,j)
  40.                         i=i+1
  41.                 }
  42. }
  43.         swap(a,pivotIndex,i-1)
  44.         return i-1
  45. }
  46.                
  47.  
  48. func inOrder(a []int) bool {
  49.         if len(a) > 0 {
  50.                 prev := a[0]
  51.                 for i := 1; i < len(a); i++ {
  52.                         if a[i] < prev {
  53.                                 return false
  54.                         }
  55.                         prev = a[i]
  56.                 }
  57.         }
  58.  
  59.         return true
  60. }
  61.  
  62.  
  63.  
  64. func main() {
  65.         file,_:=os.Open(filename)
  66.         defer file.Close()
  67.         r:=bufio.NewReader(file)
  68.         for{
  69.                 byte,_,err:=r.ReadLine()
  70.                 if err != nil {
  71.                         if err == io.EOF {
  72.                                 break
  73.             }
  74.                         return
  75.         }
  76.                 d,_:=strconv.ParseUint(string(byte),10,32)
  77.                 data=append(data,int(d))
  78.         }
  79.         quicksort(data)
  80.         fmt.Println(data[:10],counter)
  81. }