我试图快速排序问题是因为它开始将输入加到给定的n然后它停止工作 [英] I am trying to make quick sort the problem is with that it starts taking input upto given n but then it stops working

查看:75
本文介绍了我试图快速排序问题是因为它开始将输入加到给定的n然后它停止工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
using namespace::std;
void quicksort(int p,int q,int a[]);
int partition(int a[],int m,int p);
void interchange(int a[],int i,int j);
int main()
{
	int arr[10],n;
	cout<<"Enter the no of elements ";
	cin>>n;
	cout<<"Enter elements in array : ";
	for(int i=0;i<n;i++)>
	{
		cin>>arr[i];
	}
	quicksort(0,n-1,arr);
	for(int i=0;i<n;i++)>
	{
		cout<<arr[i];
	}
	return 0;

}
void quicksort(int p,int q,int a[])
{
	int j;
	if(p<q)>
	{
		j= partition(a,p,q+1);
		quicksort(p,j-1,a);
		quicksort(j+1,q,a);
	}
}
int partition(int a[],int m,int p)
{
	int V=a[m],i=m,j=p;
	while(i<j)>
	{
		while(a[i]<=V&&i<p)>
		{
			i=i+1;
		}
		while(a[i]>V)
		{
			j=j-1;
		}
		if(i<j)>
		{
			interchange(a,i,j);
		}
	}
	int temp=a[m];
	a[m]=a[j];
	a[j]=temp;
	return i;
}
void interchange(int a[],int i,int j)
{
	int temp;
	temp=a[i];
	a[i]=a[j];
	a[j]=temp;
}





我的尝试:



i试图用任何no替换n但是它还没有工作



What I have tried:

i have tried to replace n by any no but then also its not working

推荐答案

以下循环:

while(a[i]>V)
{
    j=j-1;
}

可能导致无限循环,因为您使用 i 检查值而不是使用 j ...

can cause an infinite loop since you check the value using i instead of using j...


引用:

我试图用任何no替换n但是它还没有工作

i have tried to replace n by any no but then also its not working



我认为现在是时候停止猜测你的代码在做什么了。是时候看到你的代码正在执行并确保它能达到预期的效果。



调试器是你的朋友。它会告诉你你的代码到底在做什么。

一步一步地执行,检查变量,你会发现它有一个停止做你期望的点。

掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]

http://docs.oracle .com / javase / 7 / docs / technotes / tools / windows / jdb.html [ ^ ]

https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html [ ^ ]



潜在问题:你没有检查数值的数量是否没有达到数组的大小。



在这段代码中, a [j]被排除在排序之外:


I think it is time for you to stop guessing what your code is doing. It is time to see your code executing and ensuring that it does what you expect.

The debugger is your friend. It will show you what your code is really doing.
Follow the execution step by step, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

Potential problem: you don't check that the number of values don't exeed the size of the array.

In this code, a[j] is excluded from sorting:

j= partition(a,p,q+1);
quicksort(p,j-1,a);
quicksort(j+1,q,a);



我的错,问题不是这个。看起来你正在搞乱索引,调试器可能是查看附加内容的最佳方式。


My mistake, the problem is not this. looks like you are messing with indexes, the debugger is probably the best way to see what append.


这篇关于我试图快速排序问题是因为它开始将输入加到给定的n然后它停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆