Ruby 정렬 알고리즘 삽입 및 2단계 정렬 코드 삽입 예제
하나의 기록을 이미 정렬된 표에 삽입하여 하나의 기록을 추가하는 질서정연한 표를 얻는다.그리고 가장 관건적인 것은 현재 원소보다 큰 기록을 뒤로 이동시켜'자신'이 삽입할 위치를 비우는 것이다.n-1번 삽입이 끝난 후에 이 기록은 질서정연한 서열이다.
def insertSort(tarray)
  i=1
  while(i < tarray.size) do
   if tarray[i] < tarray[i-1]
     j=i-1
     x=tarray[i]
   #puts x.class
   #puts tarray[i].class
     tarray[i]=tarray[i-1]# 
     while(x< tarray[j].to_i) do# , 
      tarray[j+1]=tarray[j]
      #puts tarray[j].class
      j=j-1
     end
     tarray[j+1]=x
   end
   i=i+1
  end
 end
a=[5,2,6,4,7,9,8]
insertSort(a)
print a
[2, 4, 5, 6, 7, 8, 9]>Exit code: 0
final.rb:10:in `<': comparison of Fixnum with nil failed (ArgumentError)
처음에 나는 매우 곤혹스러워서 x.class,tarray[j]를 출력했다.class, 그러나 이 두 출력은 모두 Fixnum입니다.나중에 루비의 Array 클래스는 다른 것과 다르다. 루비에서 하나의 Array 대상에 서로 다른 유형의 원소를 저장할 수 있다. a의 원소가 x에 값을 부여한 후에 x와 비교된 a[i]가 Fixnum 유형인지 확인할 수 없기 때문에 오류를 보고하는 것은 단지 나의 이해일 뿐이다.진급
2소켓 삽입 정렬:
def two_way_sort data
 first,final = 0,0
 temp = []
 temp[0] = data[0]
 result = []
 len = data.length
 for i in 1..(len-1)
  if data[i]>=temp[final]
   final +=1
   temp[final] = data[i]
  elsif data[i]<= temp[first]
   first = (first -1 + len)%len
   temp[first] = data[i]
  else
   if data[i]<temp[0]
    low = first
    high = len -1
   
    while low <=high do
     m = (low + high)>>1
     if data[i]>temp[m]
      low = m + 1
     else
      high = m -1
     end
    end
    
    j = first - 1
    first -=1
    while j < high do
     temp[j] = temp[j+1]
     j +=1
    end
 
    temp[high] = data[i]
   else
    low =0
    high = final
    while low <=high do
     m =(low + high)>>1
     if data[i]>=temp[m]
      low = m + 1
     else
      high = m - 1
     end
    end
    j = final + 1
    final +=1
    while j > low do
     temp[j] = temp[j-1]
     j -=1
    end 
    temp[low] = data[i]
   end
  end 
  p temp 
 end
 i = 0
 for j in first..(len - 1)
  result[i] = temp[j]
  i +=1
 end
 for j in 0..final
  result[i] = temp[j]
  i +=1
 end
 return result
end
data = [4,1,5,6,7,2,9,3,8].shuffle
p data
result = two_way_sort data
p result
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Ruby의 단일 메소드 및 단일 클래스 상세 정보단일 방법 Ruby는 단일 객체에만 적용되는 단일 객체 추가 방법을 단일 방법이라고 합니다. 또한 위에서 사용한 정의 방법 외에 Object#define_를 통해singleton_method 방법으로 단일 방법 정의...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.