如果我的数组已经部分排序,如何跳过排序程序中数组的一部分
因此,我们在班上教授了泡沫排序,
!Sorting n real numbers
program bubblesort
implicit none
integer::i,j,n
integer,allocatable,dimension(:)::A
write(*,*)"Enter the number of elements"
read(*,*)n
allocate (A(n))
write(*,*)"Enter the numbers"
read(*,*)(A(i),i=1,n)
do while (n>1)
do i=1,n-1
if(A(i) > A(i+1)) then
j = A(i)
A(i) = A(i+1)
A(i+1) = j
endif
enddo
n = n-1
enddo
write(*,*)"The sorted array is - ",A
end program
现在我有这个代码,我的教授要求我修改它,如果要排序的给定阵列的一部分已经在正确的位置,那么我们应该跳过那部分,例如假设我的数组是5 3 1 2 4 6 7 8
,这里6 7 8
在正确的位置,因此我们如何编写一个程序,以便它自动跳过这些最后一个3个要素。
我在网上无处不在,但是我找不到它如何以这种方式优化气泡排序,我只能找到方法来检查整个阵列是否已排序,然后在发生这种情况时如何结束排序。
感谢提前的帮助!
So we were taught bubble sort in our class and I have this code
!Sorting n real numbers
program bubblesort
implicit none
integer::i,j,n
integer,allocatable,dimension(:)::A
write(*,*)"Enter the number of elements"
read(*,*)n
allocate (A(n))
write(*,*)"Enter the numbers"
read(*,*)(A(i),i=1,n)
do while (n>1)
do i=1,n-1
if(A(i) > A(i+1)) then
j = A(i)
A(i) = A(i+1)
A(i+1) = j
endif
enddo
n = n-1
enddo
write(*,*)"The sorted array is - ",A
end program
now my professor asked me to modify it in a way that if part of the given array to be sorted is already in the correct place then we should skip that part, for example say my array is 5 3 1 2 4 6 7 8
, here 6 7 8
are in the correct place so how can we write a program such that it automatically skips these last 3 elements.
I've looked everywhere online but I couldn't find how it optimize bubble sort in this way, I could only find ways to check if the entire array is sorted and then how to end the sorting when that happens.
Thanks for the help in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我能够使用2个不同的子例程来解决此问题,一个是为了通过阵列进行的第一个检查,并检查末尾的多少元素不需要进一步的分类,然后我在泡沫排列的其余部分中使用了另一个子例程
。是确定K的第一个子例程,它可以找到降低的范围
,这是针对常规气泡排序使用
我的主程序中的阵列中的降低范围
I was able to solve this using 2 different subroutines, one is for the first check which goes through the array and checks how many elements at the end do not need further sorting and then I used another subroutine for the rest of the bubble sort runs
This is the first subroutine which determines k, which finds the reduced range
And this is for the regular bubble sort using the reduced range in the array
In my main program I just call these two consecutively