1. 程式人生 > >Fortran 和 c++ 的 插入排序 insertion sort 程式碼

Fortran 和 c++ 的 插入排序 insertion sort 程式碼

插入排序法,Fortran程式碼如下:

subroutine insertionsort(a)
   implicit none 
   integer :: a(:)
   integer :: temp
   integer :: n , ii,jj
   n=size(a)

   do ii=2,n
      do jj=ii,2,-1
         if(a(jj) < a(jj-1)) then
            temp = a(jj)
            a(jj) = a(jj-1)
            a(jj-1) = temp 
         end if 
      end do 
   end do 

end subroutine insertionsort 

program main 

   implicit none 

   interface 
      subroutine insertionsort(a)
         integer :: a(:) 
      end subroutine 
   end interface 

   integer,allocatable :: a(:)
   integer :: number 

   write(*,*) "input number of numbers:"
   read(*,*) number 
   allocate(a(number))

   write(*,*) "input numbers: "
   read(*,*) a 

   call insertionsort(a)
   write(*,*) a 

end program 

嘗試給100萬個0-99的整數排序
每執行1000個記一次時間
程式碼如下:

subroutine insertionsort(a)
   implicit none 
   integer :: a(:)
   integer :: temp
   integer :: n , ii,jj
   real    :: t1,t2 
   n=size(a)

!    write(*,*) a
   open(unit=15,file="time.txt")
   do ii=2,n

      if (mod(ii,1000)==0) then 
         call cpu_time(t2)
         write(*,*) ii , "time: ",t2-t1
         write(15,*) ii/1000,t2-t1
         t1=t2
      end if 

      do jj=ii,2,-1
         if(a(jj) < a(jj-1)) then
            temp = a(jj)
            a(jj) = a(jj-1)
            a(jj-1) = temp 
         end if 
      end do 
   end do 

end subroutine insertionsort 

program main 

   implicit none 

   interface 
      subroutine insertionsort(a)
         integer :: a(:) 
      end subroutine 
   end interface 

   integer,allocatable :: a(:)
   integer  :: number ,ii
   real     :: t2,t1

!    write(*,*) "input number of numbers:"
!    read(*,*) number 
   number=1000000
   allocate(a(number))

!    write(*,*) "input numbers: "
!    read(*,*) a 
   open(12,file="r.txt")
   open(unit=13,file="out.txt")
   read(12,*) a 
   call cpu_time(t1)

   call insertionsort(a)
   call cpu_time(t2)
   write(*,*) t2-t1
   do ii=1,number 
    write(13,*) a(ii)
   enddo 

end program 

每1000次的迴圈記一次時間,畫圖
在這裡插入圖片描述
可以看出插入排序法的時間複雜度為O(N^2)

c++程式碼

#include <fstream>
#include <iostream>
using namespace std;

int main ()
{
   int a[1000000];
   int i;
   int ii , jj ,kk ;
   int temp;
   float t1,t2;

   ifstream infile;
   infile.open("r.txt");

   ofstream outfile;
   outfile.open("out.txt"
); for(i=0;i<999999;i++){ infile >> a[i]; // if(i%100==0){ // cout << i << endl; // } } infile >> a[i]; cout << a[2]<< ' '<<a[999999]<< endl; for(ii=2;ii<=999999;ii++){ if(ii%1000==0){ t2=clock()/1000000.; cout << ii << ' ' << t2-t1 << endl; outfile << ii << ' ' << t2-t1 << endl; t1=t2; }; for(jj=ii;jj>=2;jj--){ if(a[jj]<a[jj-1]){ temp=a[jj]; a[jj]=a[jj-1]; a[jj-1]=temp; }; }; }; return 0; }

在這裡插入圖片描述
似乎c++比Fortran快一點